@owf/mdoc 0.6.0-alpha-20260225221529

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["z","z","#data","#buffer","z","z","z","z","z","z","z","z","z","z","z","z","z","addExtension","z","addExtension","z","z","z","z"],"sources":["../src/utils/zod-error.ts","../src/error/ValidationError.ts","../src/utils/zod.ts","../src/cbor/parser.ts","../src/cbor/data-item.ts","../src/cbor/cbor-structure.ts","../src/cbor/models/date.ts","../src/cbor/models/date-only.ts","../src/cose/error.ts","../src/cose/headers/defaults.ts","../src/cose/headers/protected-headers.ts","../src/cose/headers/unprotected-headers.ts","../src/cose/key/curve.ts","../src/utils/transformers.ts","../src/utils/typed-map.ts","../src/cose/key/key-operation.ts","../src/cose/key/key-type.ts","../src/cose/key/jwk.ts","../src/cose/key/key.ts","../src/mdoc/models/ble-options.ts","../src/mdoc/models/nfc-options.ts","../src/mdoc/models/wifi-options.ts","../src/mdoc/models/device-retrieval-method.ts","../src/mdoc/models/protocol-info.ts","../src/mdoc/models/e-device-key.ts","../src/mdoc/models/security.ts","../src/mdoc/models/oidc.ts","../src/mdoc/models/web-api.ts","../src/mdoc/models/server-retrieval-method.ts","../src/mdoc/models/device-engagement.ts","../src/mdoc/models/e-reader-key.ts","../src/mdoc/models/handover.ts","../src/mdoc/models/nfc-handover.ts","../src/mdoc/models/oid4vp-dc-api-draft24-handover-info.ts","../src/mdoc/models/oid4vp-dc-api-handover.ts","../src/mdoc/models/oid4vp-dc-api-handover-info.ts","../src/mdoc/models/oid4vp-draft18-handover.ts","../src/mdoc/models/oid4vp-handover.ts","../src/mdoc/models/oid4vp-handover-info.ts","../src/mdoc/models/oid4vp-iae-handover.ts","../src/mdoc/models/oid4vp-iae-handover-info.ts","../src/mdoc/models/qr-handover.ts","../src/mdoc/models/session-transcript.ts","../src/cose/mac0.ts","../src/cose/sign1.ts","../src/mdoc/errors.ts","../src/mdoc/check-callback.ts","../src/mdoc/models/device-signed-items.ts","../src/mdoc/models/device-namespaces.ts","../src/mdoc/models/device-authentication.ts","../src/mdoc/models/device-mac.ts","../src/mdoc/models/device-signature.ts","../src/mdoc/models/device-auth.ts","../src/mdoc/models/device-key.ts","../src/mdoc/models/key-authorizations.ts","../src/mdoc/models/key-info.ts","../src/mdoc/models/device-key-info.ts","../src/mdoc/models/items-request.ts","../src/mdoc/models/reader-authentication.ts","../src/mdoc/models/reader-auth.ts","../src/mdoc/models/doc-request.ts","../src/mdoc/models/device-request.ts","../src/utils/findIssuerSigned.ts","../src/mdoc/models/issuer-signed-item.ts","../src/mdoc/models/issuer-namespaces.ts","../src/utils/limitDisclosure.ts","../src/utils/verifyDocRequestsWithIssuerSigned.ts","../src/mdoc/models/device-signed.ts","../src/mdoc/models/validity-info.ts","../src/mdoc/models/value-digests.ts","../src/mdoc/models/mobile-security-object.ts","../src/mdoc/models/issuer-auth.ts","../src/mdoc/models/issuer-signed.ts","../src/mdoc/models/document.ts","../src/mdoc/models/document-error.ts","../src/mdoc/models/device-response.ts","../src/mdoc/models/error-items.ts","../src/mdoc/models/errors.ts","../src/mdoc/builders/device-signed-builder.ts","../src/utils/randomUnsignedInteger.ts","../src/mdoc/builders/issuer-signed-builder.ts","../src/holder.ts","../src/issuer.ts","../src/verifier.ts"],"sourcesContent":["import z from 'zod'\nimport { createErrorMap, fromError } from 'zod-validation-error'\n\nz.config({\n customError: createErrorMap(),\n})\n\nexport function formatZodError(error?: z.ZodError): string {\n if (!error) return ''\n\n return fromError(error, {\n prefix: '',\n prefixSeparator: '✖ ',\n issueSeparator: '\\n✖ ',\n unionSeparator: '\\n OR ✖ ',\n }).toString()\n}\n","import type { ZodError } from 'zod'\nimport { formatZodError } from '../utils/zod-error'\n\nexport class ValidationError extends Error {\n public zodError: ZodError | undefined\n\n constructor(message: string, zodError?: ZodError) {\n super(message)\n\n const formattedError = zodError ? formatZodError(zodError) : ''\n this.message = `${message}\\n${formattedError}`\n\n Object.defineProperty(this, 'zodError', {\n value: zodError,\n writable: false,\n enumerable: false,\n })\n }\n}\n","import z from 'zod'\nimport type { $ZodType } from 'zod/v4/core'\nimport { ValidationError } from '../error/ValidationError'\n\nexport const zUint8Array = z.instanceof<typeof Uint8Array<ArrayBufferLike>>(Uint8Array)\n\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\ntype ZodTypeAny = $ZodType<any, any, any>\n\nexport function parseStructureWithErrorHandling<Schema extends ZodTypeAny>(\n structureName: string,\n schema: Schema,\n data: unknown,\n customErrorMessage?: string\n): z.infer<Schema> {\n const parseResult = z.safeParse(schema, data)\n\n if (!parseResult.success) {\n throw new ValidationError(customErrorMessage ?? `Error decoding ${structureName}`, parseResult.error)\n }\n\n return parseResult.data\n}\n\nexport function decodeStructureWithErrorHandling<Schema extends ZodTypeAny>(\n structureName: string,\n schema: Schema,\n data: z.input<Schema>,\n customErrorMessage?: string\n): z.infer<Schema> {\n const decodeResult = z.safeDecode(schema, data)\n\n if (!decodeResult.success) {\n throw new ValidationError(customErrorMessage ?? `Error decoding ${structureName}`, decodeResult.error)\n }\n\n return decodeResult.data\n}\n\nexport function encodeStructureWithErrorHandling<Schema extends ZodTypeAny>(\n structureName: string,\n schema: Schema,\n data: z.output<Schema>,\n customErrorMessage?: string\n): z.input<Schema> {\n const encodeResult = z.safeEncode(schema, data)\n\n if (!encodeResult.success) {\n throw new ValidationError(customErrorMessage ?? `Error encoding ${structureName}`, encodeResult.error)\n }\n\n return encodeResult.data\n}\n","import { Encoder, type Options } from 'cbor-x'\nimport { DataItem } from './data-item'\n\nexport type CborOptions = Options & {\n unwrapTopLevelDataItem?: boolean\n}\n\nconst encoderDefaults: CborOptions = {\n tagUint8Array: false,\n useRecords: false,\n mapsAsObjects: false,\n unwrapTopLevelDataItem: true,\n variableMapSize: true,\n}\n\nexport const cborDecode = <T>(input: Uint8Array, options: CborOptions = encoderDefaults): T => {\n const params = { ...encoderDefaults, ...options }\n const enc = new Encoder(params)\n const decoded = enc.decode(input)\n return params.unwrapTopLevelDataItem && typeof decoded === 'object' && decoded instanceof DataItem\n ? (decoded.data as T)\n : (decoded as T)\n}\n\nexport const cborEncode = (obj: unknown, options: Options = encoderDefaults): Uint8Array => {\n const params = { ...encoderDefaults, ...options }\n const enc = new Encoder(params)\n return Uint8Array.from(enc.encode(obj))\n}\n","import { addExtension } from 'cbor-x'\nimport z from 'zod'\nimport { cborDecode, cborEncode } from './parser'\n\nexport const zDataItemCodec = (outputSchema: z.ZodType) =>\n z.codec(z.instanceof(DataItem), outputSchema, {\n encode: (data) => DataItem.fromData(data),\n decode: (dataItem) => dataItem.data,\n })\n\nexport type DataItemOptions<T = unknown> =\n | {\n data: T\n buffer: Uint8Array\n }\n | { data: T }\n | { buffer: Uint8Array }\n\n/**\n * DataItem is an extension defined https://www.rfc-editor.org/rfc/rfc8949.html#name-encoded-cbor-data-item\n * > Sometimes it is beneficial to carry an embedded CBOR data item that is\n * > not meant to be decoded immediately at the time the enclosing data item is being decoded.\n *\n * The idea of this class is to provide lazy encode and decode of cbor data.\n *\n * Due to a bug in the cbor-x library, we are eagerly encoding the data in the constructor.\n * https://github.com/kriszyp/cbor-x/issues/83\n *\n */\nexport class DataItem<T = unknown> {\n #data?: T\n #buffer: Uint8Array\n\n public constructor(options: DataItemOptions<T>) {\n if (!('data' in options) && !('buffer' in options)) {\n throw new Error('DataItem must be initialized with either the data or a buffer')\n }\n\n if ('data' in options) this.#data = options.data\n this.#buffer = 'buffer' in options ? options.buffer : cborEncode(options.data)\n }\n\n public get data(): T {\n if (!this.#data) {\n this.#data = cborDecode(this.#buffer) as T\n }\n return this.#data\n }\n\n public get buffer(): Uint8Array {\n return this.#buffer\n }\n\n public static fromData<T>(data: T): DataItem<T> {\n return new DataItem({ data })\n }\n\n public static fromBuffer<T>(buffer: Uint8Array): DataItem<T> {\n return new DataItem({ buffer })\n }\n}\n\naddExtension({\n Class: DataItem,\n tag: 24,\n encode: (instance: DataItem<unknown>, encode) => {\n return encode(instance.buffer)\n },\n decode: (buffer: Uint8Array): object => {\n return DataItem.fromBuffer(buffer)\n },\n})\n","import { z } from 'zod'\nimport {\n decodeStructureWithErrorHandling,\n encodeStructureWithErrorHandling,\n parseStructureWithErrorHandling,\n} from '../utils/zod'\nimport { DataItem } from './data-item'\nimport { cborDecode, cborEncode } from './parser'\n\nexport type CborEncodeOptions = {\n asDataItem?: boolean\n}\n\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\nexport type AnyCborStructure = CborStructure<any, any>\n\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\nexport type EncodedStructureType<T> = T extends CborStructure<infer EncodedStructure, unknown> ? EncodedStructure : any\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\nexport type DecodedStructureType<T> = T extends CborStructure<unknown, infer DecodedStructure> ? DecodedStructure : any\n\nexport type CborStructureStaticThis<T extends AnyCborStructure> = {\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n new (structure: any): T\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n encodingSchema: z.ZodType<any, any, any> | undefined\n fromEncodedStructure: (encodedStructure: EncodedStructureType<T>) => { decodedStructure: DecodedStructureType<T> }\n}\n\nexport class CborStructure<EncodedStructure = unknown, DecodedStructure = EncodedStructure> {\n protected structure: DecodedStructure\n\n public constructor(structure: DecodedStructure) {\n this.structure = structure\n }\n\n public get decodedStructure(): DecodedStructure {\n return this.structure\n }\n\n /**\n * Static getter for the Zod codec schema that defines the CBOR structure.\n * Subclasses CAN override this to provide their specific schema for automatic encoding/decoding.\n * The schema should be a Zod schema or codec that handles validation and transformation.\n * If not provided, subclasses must override encode(), decode(), and fromEncodedStructure().\n */\n public static get encodingSchema(): z.ZodType | undefined {\n return undefined\n }\n\n /**\n * Returns the encoded structure that will be serialized to CBOR.\n * By default, returns the protected structure property.\n * Override if custom encoding logic is needed.\n */\n public get encodedStructure(): EncodedStructure {\n const encodingSchema = (this.constructor as typeof CborStructure).encodingSchema\n if (!encodingSchema) {\n throw new Error('encodedStructure must be implemented when encodingSchema is not provided')\n }\n\n return encodeStructureWithErrorHandling(this.constructor.name, encodingSchema, this.structure) as EncodedStructure\n }\n\n /**\n * Encodes this structure to CBOR bytes.\n */\n public encode(options?: CborEncodeOptions): Uint8Array {\n const encodedStructure = options?.asDataItem ? DataItem.fromData(this.encodedStructure) : this.encodedStructure\n\n return cborEncode(encodedStructure)\n }\n\n /**\n * Decodes CBOR bytes into a structure instance.\n * Uses the encodingSchema's decode() method to validate and transform the decoded data.\n */\n public static decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n const rawStructure = cborDecode(bytes)\n\n // May feel weird, but using new this makes TypeScript understand we may return a subclass\n return new this(this.fromEncodedStructure(rawStructure as EncodedStructureType<T>).decodedStructure)\n }\n\n /**\n * Creates a structure instance from the encoded CBOR structure (after calling cborDecode).\n *\n * Uses the encodingSchema's decode() method to validate and transform the structure if available.\n * Otherwise, subclasses must override this method.\n */\n public static fromEncodedStructure<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n encodedStructure: EncodedStructureType<T>\n ): T {\n if (!this.encodingSchema) {\n throw new Error('fromEncodedStructure must be implemented when encodingSchema is not provided')\n }\n\n return new this(decodeStructureWithErrorHandling(this.name, this.encodingSchema, encodedStructure))\n }\n\n public static fromDataItem<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, dataItem: unknown): T {\n return new this(\n parseStructureWithErrorHandling(\n this.name,\n z\n .instanceof(DataItem)\n .transform((di) => di.data)\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n .transform((d) => this.fromEncodedStructure(d as any).decodedStructure),\n dataItem,\n `Error decoding ${this.name} from DateItem`\n )\n )\n }\n\n /**\n * Creates a structure instance from the decoded structure.\n *\n * Uses the encodingSchema's parse method to validate the structure if available.\n * Otherwise, subclasses must override this method.\n */\n public static fromDecodedStructure<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n decodedStructure: DecodedStructureType<T>\n ): T {\n const encodingSchema = this.encodingSchema\n if (!encodingSchema) {\n throw new Error('fromDecodedStructure must be implemented when encodingSchema is not provided')\n }\n\n // When the schema is a codec, we need to validate it against the output schema, not the input schema\n const decodedSchema = encodingSchema instanceof z.ZodPipe ? encodingSchema.out : encodingSchema\n\n return new this(parseStructureWithErrorHandling(this.name, decodedSchema, decodedStructure))\n }\n}\n","import { addExtension } from 'cbor-x'\n\n// tdate data item shall contain a date-time string as specified in RFC 3339 (with no fraction of seconds)\n// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6\naddExtension({\n Class: Date,\n tag: 0,\n encode: (date: Date, encode) => encode(`${date.toISOString().split('.')[0]}Z`),\n decode: (isoStringDateTime: string) => new Date(isoStringDateTime),\n})\n","import { addExtension } from 'cbor-x'\n\nconst customInspectSymbol = Symbol.for('nodejs.util.inspect.custom')\nexport class DateOnly {\n private date: Date\n\n public constructor(date?: string) {\n this.date = date ? new Date(date) : new Date()\n }\n\n get [Symbol.toStringTag]() {\n return DateOnly.name\n }\n\n toString() {\n return this.toISOString()\n }\n\n toJSON() {\n return this.toISOString()\n }\n\n toISOString(): string {\n return this.date.toISOString().split('T')[0]\n }\n\n [customInspectSymbol](): string {\n return this.toISOString()\n }\n}\n\n// full-date data item shall contain a full-date string as specified in RFC 3339\n// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6\naddExtension({\n Class: DateOnly,\n tag: 1004,\n encode: (date: DateOnly, encode) => encode(date.toISOString()),\n decode: (isoStringDate: string) => new DateOnly(isoStringDate),\n})\n","// biome-ignore format: no explanation\nclass CoseError extends Error {\n constructor(message: string = new.target.name) {\n super(message)\n }\n}\n\nexport class CoseUnsupportedMacError extends CoseError {}\nexport class CoseInvalidSignatureError extends CoseError {}\nexport class CoseInvalidAlgorithmError extends CoseError {}\nexport class CosePayloadMustBeNullError extends CoseError {}\nexport class CosePayloadMustBeDefinedError extends CoseError {}\nexport class CosePayloadInvalidStructureError extends CoseError {}\nexport class CoseInvalidTypeForKeyError extends CoseError {}\nexport class CoseInvalidValueForKtyError extends CoseError {}\nexport class CoseInvalidKtyForRawError extends CoseError {}\nexport class CoseXNotDefinedError extends CoseError {}\nexport class CoseYNotDefinedError extends CoseError {}\nexport class CoseDNotDefinedError extends CoseError {}\nexport class CoseKNotDefinedError extends CoseError {}\nexport class CoseEphemeralMacKeyIsRequiredError extends CoseError {}\nexport class CoseCertificateNotFoundError extends CoseError {}\nexport class CoseKeyTypeNotSupportedForPrivateKeyExtractionError extends CoseError {}\n","export enum Header {\n Algorithm = 1,\n Critical = 2,\n ContentType = 3,\n KeyId = 4,\n Iv = 5,\n PartialIv = 6,\n CounterSignature = 7,\n CounterSignature0 = 9,\n CounterSignatureV2 = 11,\n CounterSignature0V2 = 12,\n X5Bag = 32,\n X5Chain = 33,\n X5T = 34,\n X5U = 35,\n}\n\nexport enum SignatureAlgorithm {\n EdDSA = -8,\n ES256 = -7,\n ES384 = -35,\n ES512 = -36,\n PS256 = -37,\n PS384 = -38,\n PS512 = -39,\n RS256 = -257,\n RS384 = -258,\n RS512 = -259,\n}\n\nexport enum MacAlgorithm {\n HS256 = 5,\n HS384 = 6,\n HS512 = 7,\n}\n\nexport enum EncryptionAlgorithm {\n A128GCM = 1,\n A192GCM = 2,\n A256GCM = 3,\n Direct = -6,\n}\n\nexport type DigestAlgorithm = 'SHA-256' | 'SHA-384' | 'SHA-512'\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport { cborDecode, cborEncode } from '../../cbor/parser.js'\nimport { zUint8Array } from '../../utils/zod.js'\n\n// TODO: typedMap with known keys (Header enum)\n\nexport const protectedHeadersEncodedStructure = zUint8Array\nexport const protectedHeadersDecodedStructure = z.map(z.number(), z.unknown())\n\nexport type ProtectedHeadersDecodedStructure = z.infer<typeof protectedHeadersDecodedStructure>\nexport type ProtectedHeadersEncodedStructure = z.infer<typeof protectedHeadersEncodedStructure>\n\nexport type ProtectedHeaderOptions = {\n protectedHeaders?: ProtectedHeadersDecodedStructure\n}\n\nexport class ProtectedHeaders extends CborStructure<\n ProtectedHeadersEncodedStructure,\n ProtectedHeadersDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(protectedHeadersEncodedStructure, protectedHeadersDecodedStructure, {\n // TODO: Senders SHOULD encode a zero-length map as a zero-length string rather than as a zero-length map\n encode: (decoded) => cborEncode(decoded) as Uint8Array<ArrayBuffer>,\n decode: (encoded) => cborDecode(encoded),\n })\n }\n\n public get headers() {\n return this.structure\n }\n\n public static create(options: ProtectedHeaderOptions) {\n return this.fromDecodedStructure(options.protectedHeaders ?? new Map())\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\n\nexport const unprotectedHeadersStructure = z.map(z.number(), z.unknown())\n\nexport type UnprotectedHeadersStructure = z.infer<typeof unprotectedHeadersStructure>\n\nexport type UnprotectedHeaderOptions = {\n unprotectedHeaders?: UnprotectedHeadersStructure\n}\n\nexport class UnprotectedHeaders extends CborStructure<UnprotectedHeadersStructure> {\n public static override get encodingSchema() {\n return unprotectedHeadersStructure\n }\n\n public get headers() {\n return this.structure\n }\n\n public static create(options: UnprotectedHeaderOptions) {\n return this.fromDecodedStructure(options.unprotectedHeaders ?? new Map())\n }\n}\n","export enum Curve {\n 'P-256' = 1,\n 'P-384' = 2,\n 'P-521' = 3,\n X25519 = 4,\n X448 = 5,\n Ed25519 = 6,\n Ed448 = 7,\n}\n","const BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n\nconst bytesToBase64 = (bytes: Uint8Array): string => {\n let result = ''\n let i: number\n\n for (i = 0; i < bytes.length - 2; i += 3) {\n const chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]\n result += BASE64_CHARS[(chunk >> 18) & 63]\n result += BASE64_CHARS[(chunk >> 12) & 63]\n result += BASE64_CHARS[(chunk >> 6) & 63]\n result += BASE64_CHARS[chunk & 63]\n }\n\n // Handle padding\n if (i < bytes.length) {\n const chunk = (bytes[i] << 16) | (i + 1 < bytes.length ? bytes[i + 1] << 8 : 0)\n result += BASE64_CHARS[(chunk >> 18) & 63]\n result += BASE64_CHARS[(chunk >> 12) & 63]\n result += i + 1 < bytes.length ? BASE64_CHARS[(chunk >> 6) & 63] : '='\n result += '='\n }\n\n return result\n}\n\nconst base64ToBytes = (base64: string): Uint8Array => {\n // Validate input - only base64 characters and padding are allowed\n const validBase64Regex = /^[A-Za-z0-9+/]*={0,2}$/\n if (!validBase64Regex.test(base64)) {\n throw new Error('Invalid base64 string: contains invalid characters')\n }\n\n // Remove padding\n const cleanBase64 = base64.replace(/=/g, '')\n const length = cleanBase64.length\n const bytes = new Uint8Array((length * 3) >> 2)\n\n let byteIndex = 0\n for (let i = 0; i < length; i += 4) {\n const a = BASE64_CHARS.indexOf(cleanBase64[i])\n const b = BASE64_CHARS.indexOf(cleanBase64[i + 1])\n const c = i + 2 < length ? BASE64_CHARS.indexOf(cleanBase64[i + 2]) : 0\n const d = i + 3 < length ? BASE64_CHARS.indexOf(cleanBase64[i + 3]) : 0\n\n bytes[byteIndex++] = (a << 2) | (b >> 4)\n if (i + 2 < length) bytes[byteIndex++] = ((b & 15) << 4) | (c >> 2)\n if (i + 3 < length) bytes[byteIndex++] = ((c & 3) << 6) | d\n }\n\n return bytes\n}\n\nconst bytesToBase64Url = (bytes: Uint8Array): string => {\n return bytesToBase64(bytes).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '')\n}\n\nconst base64UrlToBytes = (base64url: string): Uint8Array => {\n // Validate input - only base64url characters (no padding) are allowed\n const validBase64UrlRegex = /^[A-Za-z0-9_-]*$/\n if (!validBase64UrlRegex.test(base64url)) {\n throw new Error('Invalid base64url string: contains invalid characters')\n }\n\n // Convert base64url to base64\n let base64 = base64url.replace(/-/g, '+').replace(/_/g, '/')\n // Add padding if needed\n while (base64.length % 4) {\n base64 += '='\n }\n return base64ToBytes(base64)\n}\n\nconst bytesToHex = (bytes: Uint8Array): string => {\n let result = ''\n for (let i = 0; i < bytes.length; i++) {\n const hex = bytes[i].toString(16)\n result += hex.length === 1 ? `0${hex}` : hex\n }\n return result\n}\n\nconst hexToBytes = (hex: string): Uint8Array => {\n // Validate input - only hex characters are allowed, and length must be even\n const validHexRegex = /^[0-9a-fA-F]*$/\n if (!validHexRegex.test(hex)) {\n throw new Error('Invalid hex string: contains invalid characters')\n }\n if (hex.length % 2 !== 0) {\n throw new Error('Invalid hex string: length must be even')\n }\n\n const bytes = new Uint8Array(hex.length / 2)\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(hex.substring(i, i + 2), 16)\n }\n return bytes\n}\n\nexport const base64 = {\n decode: base64ToBytes,\n encode: bytesToBase64,\n}\n\nexport const base64url = {\n decode: base64UrlToBytes,\n encode: bytesToBase64Url,\n}\n\nexport const hex = {\n decode: hexToBytes,\n encode: bytesToHex,\n}\n\nexport const bytesToString = (bytes: Uint8Array): string => {\n let result = ''\n let i = 0\n\n while (i < bytes.length) {\n const byte1 = bytes[i++]\n\n if (byte1 < 0x80) {\n // Single byte character\n result += String.fromCharCode(byte1)\n } else if (byte1 < 0xe0) {\n // Two byte character\n const byte2 = bytes[i++]\n result += String.fromCharCode(((byte1 & 0x1f) << 6) | (byte2 & 0x3f))\n } else if (byte1 < 0xf0) {\n // Three byte character\n const byte2 = bytes[i++]\n const byte3 = bytes[i++]\n result += String.fromCharCode(((byte1 & 0x0f) << 12) | ((byte2 & 0x3f) << 6) | (byte3 & 0x3f))\n } else {\n // Four byte character - convert to surrogate pair\n const byte2 = bytes[i++]\n const byte3 = bytes[i++]\n const byte4 = bytes[i++]\n const codePoint = ((byte1 & 0x07) << 18) | ((byte2 & 0x3f) << 12) | ((byte3 & 0x3f) << 6) | (byte4 & 0x3f)\n const surrogate1 = 0xd800 + ((codePoint - 0x10000) >> 10)\n const surrogate2 = 0xdc00 + ((codePoint - 0x10000) & 0x3ff)\n result += String.fromCharCode(surrogate1, surrogate2)\n }\n }\n return result\n}\n\nexport const stringToBytes = (str: string): Uint8Array => {\n const bytes: number[] = []\n\n for (let i = 0; i < str.length; i++) {\n let codePoint = str.charCodeAt(i)\n\n // Handle surrogate pairs\n if (codePoint >= 0xd800 && codePoint <= 0xdbff && i + 1 < str.length) {\n const low = str.charCodeAt(i + 1)\n if (low >= 0xdc00 && low <= 0xdfff) {\n codePoint = 0x10000 + ((codePoint - 0xd800) << 10) + (low - 0xdc00)\n i++\n }\n }\n\n if (codePoint < 0x80) {\n // Single byte\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n // Two bytes\n bytes.push(0xc0 | (codePoint >> 6))\n bytes.push(0x80 | (codePoint & 0x3f))\n } else if (codePoint < 0x10000) {\n // Three bytes\n bytes.push(0xe0 | (codePoint >> 12))\n bytes.push(0x80 | ((codePoint >> 6) & 0x3f))\n bytes.push(0x80 | (codePoint & 0x3f))\n } else {\n // Four bytes\n bytes.push(0xf0 | (codePoint >> 18))\n bytes.push(0x80 | ((codePoint >> 12) & 0x3f))\n bytes.push(0x80 | ((codePoint >> 6) & 0x3f))\n bytes.push(0x80 | (codePoint & 0x3f))\n }\n }\n\n return new Uint8Array(bytes)\n}\n\nexport const concatBytes = (byteArrays: Array<Uint8Array>): Uint8Array => {\n const totalLength = byteArrays.reduce((sum, arr) => sum + arr.length, 0)\n const result = new Uint8Array(totalLength)\n let offset = 0\n for (const arr of byteArrays) {\n result.set(arr, offset)\n offset += arr.length\n }\n return result\n}\n\nexport const compareBytes = (lhs: Uint8Array, rhs: Uint8Array) => {\n if (lhs === rhs) return true\n if (lhs.byteLength !== rhs.byteLength) return false\n return lhs.every((b, i) => b === rhs[i])\n}\n","import { z } from 'zod'\nimport type zCore from 'zod/v4/core'\n\n/**\n * TypedMap provides compile-time type safety for Maps where each key has its own specific value type.\n * Unlike Map<K, V> which has the same value type V for all keys, TypedMap<Schema, OptionalKeys>\n * allows different value types per key (heterogeneous values).\n *\n * Example:\n * type CoseKeySchema = {\n * [CoseKeyParameter.KeyType]: KeyType // number key → KeyType value\n * [CoseKeyParameter.Curve]: Curve // number key → Curve value\n * [CoseKeyParameter.X]: Uint8Array // number key → Uint8Array value\n * }\n *\n * const map = new TypedMap<CoseKeySchema>()\n * map.get(CoseKeyParameter.KeyType) // TypeScript knows this is KeyType!\n * map.get(CoseKeyParameter.Curve) // TypeScript knows this is Curve!\n * map.get(CoseKeyParameter.X) // TypeScript knows this is Uint8Array!\n *\n * @template Schema - Object type mapping keys to their value types\n * @template OptionalKeys - Union of keys that are optional (can be absent)\n */\n\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\nexport class TypedMap<Schema extends Record<PropertyKey, any>, OptionalKeys extends keyof Schema = never> {\n private readonly map: Map<keyof Schema, Schema[keyof Schema]>\n\n constructor(entries?: (readonly [keyof Schema, Schema[keyof Schema]])[] | null) {\n this.map = new Map(entries)\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n public static fromMap<Schema extends Record<PropertyKey, any>, OptionalKeys extends keyof Schema = never>(\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n map: Map<any, any>\n ) {\n return new TypedMap<Schema, OptionalKeys>(Array.from(map.entries()))\n }\n\n /**\n * Type-safe get that returns the correct value type for each key.\n * Required keys return T, optional keys return T | undefined.\n */\n get<K extends keyof Schema>(key: K): K extends OptionalKeys ? Schema[K] | undefined : Schema[K] {\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n return this.map.get(key) as any\n }\n\n /**\n * Type-safe set that ensures the value matches the key's type\n */\n set<K extends keyof Schema>(key: K, value: Schema[K]): this {\n this.map.set(key, value)\n return this\n }\n\n has(key: keyof Schema): boolean {\n return this.map.has(key)\n }\n\n delete(key: keyof Schema): boolean {\n return this.map.delete(key)\n }\n\n clear(): void {\n this.map.clear()\n }\n\n get size(): number {\n return this.map.size\n }\n\n keys(): IterableIterator<keyof Schema> {\n return this.map.keys()\n }\n\n values(): IterableIterator<Schema[keyof Schema]> {\n return this.map.values()\n }\n\n entries(): IterableIterator<[keyof Schema, Schema[keyof Schema]]> {\n return this.map.entries()\n }\n\n forEach(\n callbackfn: (value: Schema[keyof Schema], key: keyof Schema, map: Map<keyof Schema, Schema[keyof Schema]>) => void,\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n thisArg?: any\n ): void {\n this.map.forEach(callbackfn, thisArg)\n }\n\n [Symbol.iterator](): IterableIterator<[keyof Schema, Schema[keyof Schema]]> {\n return this.map[Symbol.iterator]()\n }\n\n toMap(): Map<keyof Schema, Schema[keyof Schema]> {\n return new Map(this.map)\n }\n}\n\n// Helper type to build schema from entries array\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\ntype EntriesArrayToSchema<T extends ReadonlyArray<readonly [any, any]>> = {\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n [K in T[number][0]]: Extract<T[number], readonly [K, any]>[1]\n}\n\n/**\n * This checks whether the property is exact optional. exact optional means that the value cannot be undefined, but if used\n * in an object the key can be omitted. This is important for CBOR structures, as undefined will be encoded, and thus must be\n * omitted in most cases.\n *\n * Zod recommend to check for optionality by just parsing undefined.\n */\nconst isExactOptional = (schema: z.ZodType) =>\n !schema.safeParse(undefined).success && z.object({ test: schema }).safeParse({}).success\n\ntype EntriesBase = ReadonlyArray<\n readonly [\n string | number, // for now we only allow string or number keys\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n z.ZodType<any>,\n ]\n>\n\ntype InferredEntries<Entries extends EntriesBase> = {\n [K in keyof Entries]: readonly [Entries[K][0], z.infer<Entries[K][1]>]\n}\ntype InferredSchema<Entries extends EntriesBase> = EntriesArrayToSchema<InferredEntries<Entries>>\n\ntype OptionalKeys<Entries extends EntriesBase> = Entries[number] extends infer E\n ? E extends readonly [infer K, infer V]\n ? // biome-ignore lint/suspicious/noExplicitAny: no explanation\n V extends z.ZodExactOptional<any>\n ? K\n : never\n : never\n : never\n\n/**\n * Utility function to create a typed map codec.\n * Takes an array of [key, valueSchema] entries to support any key type (including non-string keys for CBOR).\n *\n * Example:\n * const coseKeyMap = typedMap([\n * [CoseKeyParameter.KeyType, z.number()],\n * [CoseKeyParameter.Curve, z.number()],\n * [CoseKeyParameter.X, z.instanceof(Uint8Array)]\n * ] as const)\n *\n * The resulting schema validates a Map and transforms it to TypedMap<Schema, never>.\n */\nexport function typedMap<const Entries extends EntriesBase>(\n entries: Entries,\n {\n allowAdditionalKeys = true,\n encode,\n decode,\n }: {\n /**\n * Whether to allow additional keys in the typed map\n *\n * @default true\n */\n allowAdditionalKeys?: boolean\n\n /**\n * Allows overriding the encode function. The original encode method is passed as second\n * argument, so you can use this method to pre/post process\n */\n encode?: (\n decoded: TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>,\n originalEncode: (decoded: TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>) => Map<unknown, unknown>\n ) => Map<unknown, unknown>\n\n /**\n * Allows overriding the decode function. The original decode method is passed as second\n * argument, so you can use this method to pre/post process\n */\n decode?: (\n encoded: Map<unknown, unknown>,\n originalDecode: (decoded: Map<unknown, unknown>) => TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>\n ) => TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>\n } = {}\n) {\n // Create a set of required keys (non-optional) for validation\n const requiredKeys = entries.filter(([, valueSchema]) => !isExactOptional(valueSchema)).map(([key]) => key)\n\n const schemaMap = new Map(entries)\n\n const originalEncode = (decoded: TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>) => decoded.toMap()\n const originalDecode = (encoded: Map<unknown, unknown>) =>\n TypedMap.fromMap<InferredSchema<Entries>, OptionalKeys<Entries>>(encoded)\n\n return z.codec(\n // Input is untyped map\n z.map(z.unknown(), z.unknown()),\n // Output is typed map\n z\n .instanceof<typeof TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>>(TypedMap)\n .superRefine((map, ctx) => {\n // Check there's no additional keys in the map if not allowed\n const additionalKeys = Array.from(map.keys()).filter((key) => !schemaMap.has(key as string | number))\n if (additionalKeys.length > 0 && !allowAdditionalKeys) {\n for (const additionalKey of additionalKeys) {\n if (typeof additionalKey !== 'string' && typeof additionalKey !== 'number') {\n ctx.addIssue({\n code: 'invalid_key',\n origin: 'map',\n continue: true,\n path: [],\n input: map,\n issues: [],\n message: 'Key found in map that is not a string or number',\n })\n } else {\n ctx.addIssue({\n code: 'invalid_key',\n origin: 'map',\n continue: true,\n path: [additionalKey],\n input: map,\n issues: [],\n message: `Unexpected key '${additionalKey}' found in map, additional keys are not allowed.`,\n })\n }\n }\n }\n\n for (const [key, valueSchema] of schemaMap.entries()) {\n const hasKey = map.has(key)\n const value = map.get(key)\n\n if (!hasKey && requiredKeys.includes(key)) {\n ctx.addIssue({\n code: 'invalid_value',\n continue: true,\n message: `Expected key '${key}' to be defined.`,\n path: [key],\n values: [],\n input: value,\n })\n continue\n }\n\n // If key is not in the map, and also not required, skip validation\n if (!hasKey && !requiredKeys.includes(key)) {\n continue\n }\n\n const parseResult = valueSchema.safeParse(value)\n if (!parseResult.success) {\n for (const issue of parseResult.error.issues) {\n ctx.addIssue({\n ...issue,\n // NOTE: if we use numbers, zod-validation-error will use \"index\", thinking\n // it's an array, that's confusing\n path: [`${key}`, ...issue.path],\n } as zCore.$ZodSuperRefineIssue)\n }\n }\n }\n }),\n {\n decode: (input) => (decode ? decode(input, originalDecode) : originalDecode(input)),\n encode: (output) => (encode ? encode(output, originalEncode) : originalEncode(output)),\n }\n )\n}\n","export enum KeyOps {\n Sign = 1,\n Verify = 2,\n Encrypt = 3,\n Decrypt = 4,\n WrapKey = 5,\n UnwrapKey = 6,\n DeriveKey = 7,\n DeriveBits = 8,\n MACCreate = 9,\n MACVerify = 10,\n}\n","export enum KeyType {\n Okp = 1,\n Ec = 2,\n Oct = 4,\n Reserved = 0,\n}\n","import { base64url } from '../../utils'\nimport { EncryptionAlgorithm, MacAlgorithm, SignatureAlgorithm } from '../headers/defaults'\nimport { Curve } from './curve'\nimport type { CoseKeyOptions } from './key'\nimport { KeyOps } from './key-operation'\nimport { KeyType } from './key-type'\n\nconst swapMap = (map: Record<string, string>) =>\n Object.fromEntries(Object.entries(map).map(([key, value]) => [value, key]))\n\nconst swapNestedMap = (nestedMap: Record<string, Record<string, unknown>>) =>\n Object.fromEntries(\n Object.entries(nestedMap).map(([category, mappings]) => [\n category,\n Object.fromEntries(Object.entries(mappings).map(([key, value]) => [value, key])),\n ])\n )\n\nconst jwkCoseKeyMap = {\n kty: {\n OKP: KeyType.Okp,\n EC: KeyType.Ec,\n OCT: KeyType.Oct,\n },\n crv: {\n 'P-256': Curve['P-256'],\n 'p-384': Curve['P-384'],\n 'p-521': Curve['P-521'],\n X25519: Curve.X25519,\n Ed2519: Curve.Ed25519,\n Ed448: Curve.Ed448,\n },\n alg: {\n EdDSA: SignatureAlgorithm.EdDSA,\n ES256: SignatureAlgorithm.ES256,\n ES384: SignatureAlgorithm.ES384,\n ES512: SignatureAlgorithm.ES512,\n PS256: SignatureAlgorithm.PS256,\n PS384: SignatureAlgorithm.PS384,\n PS512: SignatureAlgorithm.PS512,\n RS256: SignatureAlgorithm.RS256,\n RS384: SignatureAlgorithm.RS384,\n RS512: SignatureAlgorithm.RS512,\n\n HS256: MacAlgorithm.HS256,\n HS384: MacAlgorithm.HS384,\n HS512: MacAlgorithm.HS512,\n\n A128GCM: EncryptionAlgorithm.A128GCM,\n A192GCM: EncryptionAlgorithm.A192GCM,\n A256GCM: EncryptionAlgorithm.A256GCM,\n Direct: EncryptionAlgorithm.Direct,\n },\n keyOps: {\n sign: KeyOps.Sign,\n verify: KeyOps.Verify,\n encrypt: KeyOps.Encrypt,\n decrypt: KeyOps.Decrypt,\n wrapKey: KeyOps.WrapKey,\n unwrapKey: KeyOps.UnwrapKey,\n deriveKey: KeyOps.DeriveKey,\n deriveBits: KeyOps.DeriveBits,\n mACCreate: KeyOps.MACCreate,\n mACVerify: KeyOps.MACVerify,\n },\n}\n\nconst coseKeyJwkMap = swapNestedMap(jwkCoseKeyMap)\n\nexport const jwkCoseOptionsMap: Record<string, keyof CoseKeyOptions> = {\n kty: 'keyType',\n kid: 'keyId',\n alg: 'algorithm',\n keyOps: 'keyOps',\n baseIv: 'baseIv',\n crv: 'curve',\n x: 'x',\n y: 'y',\n d: 'd',\n}\n\nexport const coseOptionsJwkMap = swapMap(jwkCoseOptionsMap)\n\nexport const jwkToCoseKey = {\n kty: (kty?: unknown) => {\n return jwkCoseKeyMap.kty[kty as keyof (typeof jwkCoseKeyMap)['kty']] ?? kty\n },\n crv: (crv?: unknown) => jwkCoseKeyMap.crv[crv as keyof (typeof jwkCoseKeyMap)['crv']] ?? crv,\n alg: (alg?: unknown) => jwkCoseKeyMap.alg[alg as keyof (typeof jwkCoseKeyMap)['alg']] ?? alg,\n kid: (kid?: unknown) => kid,\n keyOps: (keyOps?: unknown) =>\n Array.isArray(keyOps)\n ? keyOps?.map((ko) => jwkCoseKeyMap.keyOps[ko as keyof (typeof jwkCoseKeyMap)['keyOps']] ?? ko)\n : undefined,\n x: (s?: unknown) => (s && typeof s === 'string' ? base64url.decode(s) : undefined),\n y: (s?: unknown) => (s && typeof s === 'string' ? base64url.decode(s) : undefined),\n d: (s?: unknown) => (s && typeof s === 'string' ? base64url.decode(s) : undefined),\n}\n\nexport const coseKeyToJwk = {\n keyType: (keyType: KeyType) => coseKeyJwkMap.kty[keyType],\n keyId: (keyId: unknown) => keyId,\n algorithm: (algorithm?: SignatureAlgorithm | MacAlgorithm) => (algorithm ? coseKeyJwkMap.alg[algorithm] : undefined),\n keyOps: (keyOps?: unknown) =>\n keyOps && Array.isArray(keyOps) ? keyOps.map((ko) => coseKeyJwkMap.keyOps[ko]) : undefined,\n baseIv: (baseIv?: unknown) => baseIv,\n curve: (curve?: Curve) => (curve ? coseKeyJwkMap.crv[curve] : undefined),\n x: (x?: Uint8Array) => (x ? base64url.encode(x) : undefined),\n y: (y?: Uint8Array) => (y ? base64url.encode(y) : undefined),\n d: (d?: Uint8Array) => (d ? base64url.encode(d) : undefined),\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { bytesToString, concatBytes, stringToBytes, TypedMap, typedMap } from '../../utils'\nimport { zUint8Array } from '../../utils/zod'\nimport {\n CoseDNotDefinedError,\n CoseInvalidKtyForRawError,\n CoseInvalidValueForKtyError,\n CoseKeyTypeNotSupportedForPrivateKeyExtractionError,\n CoseKNotDefinedError,\n CoseXNotDefinedError,\n CoseYNotDefinedError,\n} from '../error'\nimport { Curve } from './curve'\nimport { coseKeyToJwk, coseOptionsJwkMap, jwkCoseOptionsMap, jwkToCoseKey } from './jwk'\nimport { KeyOps } from './key-operation'\nimport { KeyType } from './key-type'\n\nexport enum CoseKeyParameter {\n KeyType = 1,\n KeyId = 2,\n Algorithm = 3,\n KeyOps = 4,\n BaseIv = 5,\n\n // EC Key or Oct with K\n CurveOrK = -1,\n X = -2,\n Y = -3,\n D = -4,\n}\n\n// Zod schema for CoseKey validation\nconst coseKeySchema = typedMap([\n [CoseKeyParameter.KeyType, z.union([z.enum(KeyType), z.string()])],\n [\n CoseKeyParameter.KeyId,\n // NOTE: string is NOT allowed, but seems mDocs issued with v0.5 of this library\n // do include string keyIds. We need to ensure we don't break interop. For newly\n // created keys we ensure correct encoding.\n zUint8Array\n .or(z.string())\n .exactOptional(),\n ],\n [\n CoseKeyParameter.Algorithm,\n z\n .union([\n z.string({ error: 'Cose algorithm must be a string' }),\n z.number({ error: 'Cose algorithm must be a number' }),\n ])\n .exactOptional(),\n ],\n [CoseKeyParameter.KeyOps, z.array(z.union([z.enum(KeyOps), z.string()])).exactOptional()],\n [CoseKeyParameter.BaseIv, zUint8Array.exactOptional()],\n [CoseKeyParameter.CurveOrK, z.union([z.enum(Curve), zUint8Array]).exactOptional()],\n [CoseKeyParameter.X, zUint8Array.exactOptional()],\n [CoseKeyParameter.Y, zUint8Array.exactOptional()],\n [CoseKeyParameter.D, zUint8Array.exactOptional()],\n] as const)\n\n// Infer structure type from Zod schema\nexport type CoseKeyDecodedStructure = z.output<typeof coseKeySchema>\nexport type CoseKeyEncodedStructure = z.input<typeof coseKeySchema>\n\n// Manual options type (user-facing API)\nexport type CoseKeyOptions = {\n keyType: KeyType | string\n keyId?: string\n algorithm?: string | number\n keyOps?: Array<KeyOps | string>\n baseIv?: Uint8Array\n\n curve?: Curve\n x?: Uint8Array\n y?: Uint8Array\n\n d?: Uint8Array\n\n k?: Uint8Array\n}\n\nexport class CoseKey extends CborStructure<CoseKeyEncodedStructure, CoseKeyDecodedStructure> {\n public static override get encodingSchema() {\n return coseKeySchema\n }\n\n public get keyType() {\n return this.structure.get(CoseKeyParameter.KeyType)\n }\n\n public get keyId() {\n const keyId = this.structure.get(CoseKeyParameter.KeyId)\n return keyId instanceof Uint8Array ? bytesToString(keyId) : keyId\n }\n\n public get algorithm() {\n return this.structure.get(CoseKeyParameter.Algorithm)\n }\n\n public get keyOps() {\n return this.structure.get(CoseKeyParameter.KeyOps)\n }\n\n public get baseIv() {\n return this.structure.get(CoseKeyParameter.BaseIv)\n }\n\n public get curve() {\n if (this.keyType === KeyType.Ec || this.keyType === KeyType.Okp) {\n // Casting is needed, as it can be both Curve or K\n return this.structure.get(CoseKeyParameter.CurveOrK) as Curve | undefined\n }\n\n return undefined\n }\n\n public get x() {\n return this.structure.get(CoseKeyParameter.X)\n }\n\n public get y() {\n return this.structure.get(CoseKeyParameter.Y)\n }\n\n public get d() {\n return this.structure.get(CoseKeyParameter.D)\n }\n\n public get k() {\n if (this.keyType === KeyType.Oct) {\n return this.structure.get(CoseKeyParameter.CurveOrK) as Uint8Array | undefined\n }\n return undefined\n }\n\n public static create(options: CoseKeyOptions): CoseKey {\n const map: CoseKeyDecodedStructure = new TypedMap([[CoseKeyParameter.KeyType, options.keyType]])\n\n if (options.keyId !== undefined) {\n map.set(CoseKeyParameter.KeyId, stringToBytes(options.keyId))\n }\n\n if (options.algorithm !== undefined) {\n map.set(CoseKeyParameter.Algorithm, options.algorithm)\n }\n\n if (options.keyOps !== undefined) {\n map.set(CoseKeyParameter.KeyOps, options.keyOps)\n }\n\n if (options.baseIv !== undefined) {\n map.set(CoseKeyParameter.BaseIv, options.baseIv)\n }\n\n if (options.curve !== undefined) {\n map.set(CoseKeyParameter.CurveOrK, options.curve)\n }\n\n if (options.x !== undefined) {\n map.set(CoseKeyParameter.X, options.x)\n }\n\n if (options.y !== undefined) {\n map.set(CoseKeyParameter.Y, options.y)\n }\n\n if (options.d !== undefined) {\n map.set(CoseKeyParameter.D, options.d)\n }\n\n if (options.k !== undefined) {\n map.set(CoseKeyParameter.CurveOrK, options.k)\n }\n\n return this.fromDecodedStructure(map)\n }\n\n // TODO: add jwk zod schema\n public static fromJwk(jwk: Record<string, unknown>) {\n if (!('kty' in jwk)) {\n throw new CoseInvalidValueForKtyError('JWK does not contain required kty value')\n }\n\n const options = Object.entries(jwk).reduce((prev, [key, value]) => {\n const mappedKey = jwkCoseOptionsMap[key] ?? key\n\n const mapFunction = jwkToCoseKey[key as keyof typeof jwkToCoseKey]\n const convertedValue = mapFunction ? mapFunction(value) : value\n\n // Only include if value is not undefined\n if (convertedValue !== undefined) {\n return { ...prev, [mappedKey]: convertedValue }\n }\n\n return prev\n }, {} as CoseKeyOptions)\n\n return this.create(options)\n }\n\n public get publicKey() {\n if (this.keyType !== KeyType.Ec) {\n throw new CoseInvalidKtyForRawError()\n }\n\n if (!this.x) {\n throw new CoseXNotDefinedError()\n }\n\n if (!this.y) {\n throw new CoseYNotDefinedError()\n }\n\n return concatBytes([Uint8Array.from([0x04]), this.x, this.y])\n }\n\n public get privateKey() {\n if (this.keyType === KeyType.Ec) {\n if (!this.d) {\n throw new CoseDNotDefinedError()\n }\n\n return this.d\n }\n\n if (this.keyType === KeyType.Oct) {\n if (!this.k) {\n throw new CoseKNotDefinedError()\n }\n\n return this.k\n }\n\n throw new CoseKeyTypeNotSupportedForPrivateKeyExtractionError()\n }\n\n public get jwk(): Record<string, unknown> {\n // Convert CoseKey properties to JWK format\n const options: CoseKeyOptions = {\n keyType: this.keyType,\n keyId: this.keyId,\n algorithm: this.algorithm,\n keyOps: this.keyOps,\n baseIv: this.baseIv,\n curve: this.curve,\n x: this.x,\n y: this.y,\n d: this.d,\n k: this.k,\n }\n\n return Object.entries(options).reduce(\n (prev, [key, value]) => ({\n ...prev,\n [coseOptionsJwkMap[key] ?? key]:\n typeof coseKeyToJwk[key as keyof typeof coseKeyToJwk] === 'function'\n ? // @ts-ignore\n coseKeyToJwk[key as keyof typeof coseKeyToJwk](value)\n : undefined,\n }),\n {}\n )\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { typedMap } from '../../utils'\nimport { zUint8Array } from '../../utils/zod'\n\nenum BleOptionsKeys {\n PeripheralServerMode = 0,\n CentralClientMode = 1,\n PeripheralServerModeUuid = 10,\n CentralClientModeUuid = 11,\n PeripheralServerModeDeviceAddress = 20,\n}\n\n// BleOptions uses integer keys per spec:\n// BleOptions = {\n// 0 : bool, // Supports peripheral server mode\n// 1 : bool, // Supports central client mode\n// ? 10 : bstr, // UUID for peripheral server mode\n// ? 11 : bstr, // UUID for central client mode\n// ? 20 : bstr // BLE Device Address\n// }\nconst bleOptionsSchema = typedMap([\n [BleOptionsKeys.PeripheralServerMode, z.boolean()],\n [BleOptionsKeys.CentralClientMode, z.boolean()],\n [BleOptionsKeys.PeripheralServerModeUuid, zUint8Array.exactOptional()],\n [BleOptionsKeys.CentralClientModeUuid, zUint8Array.exactOptional()],\n [BleOptionsKeys.PeripheralServerModeDeviceAddress, zUint8Array.exactOptional()],\n] as const)\n\nexport type BleOptionsEncodedStructure = z.input<typeof bleOptionsSchema>\nexport type BleOptionsDecodedStructure = z.output<typeof bleOptionsSchema>\n\nexport type BleOptionsOptions = {\n peripheralServerMode: boolean\n centralClientMode: boolean\n peripheralServerModeUuid?: Uint8Array\n centralClientModeUuid?: Uint8Array\n peripheralServerModeDeviceAddress?: Uint8Array\n}\n\nexport class BleOptions extends CborStructure<BleOptionsEncodedStructure, BleOptionsDecodedStructure> {\n public static override get encodingSchema() {\n return bleOptionsSchema\n }\n\n public get peripheralServerMode() {\n return this.structure.get(BleOptionsKeys.PeripheralServerMode)\n }\n\n public get centralClientMode() {\n return this.structure.get(BleOptionsKeys.CentralClientMode)\n }\n\n public get peripheralServerModeUuid() {\n return this.structure.get(BleOptionsKeys.PeripheralServerModeUuid)\n }\n\n public get centralClientModeUuid() {\n return this.structure.get(BleOptionsKeys.CentralClientModeUuid)\n }\n\n public get peripheralServerModeDeviceAddress() {\n return this.structure.get(BleOptionsKeys.PeripheralServerModeDeviceAddress)\n }\n\n public static create(options: BleOptionsOptions): BleOptions {\n const map = new Map<number, unknown>([\n [BleOptionsKeys.PeripheralServerMode, options.peripheralServerMode],\n [BleOptionsKeys.CentralClientMode, options.centralClientMode],\n ])\n\n if (options.peripheralServerModeUuid !== undefined) {\n map.set(BleOptionsKeys.PeripheralServerModeUuid, options.peripheralServerModeUuid)\n }\n\n if (options.centralClientModeUuid !== undefined) {\n map.set(BleOptionsKeys.CentralClientModeUuid, options.centralClientModeUuid)\n }\n\n if (options.peripheralServerModeDeviceAddress !== undefined) {\n map.set(BleOptionsKeys.PeripheralServerModeDeviceAddress, options.peripheralServerModeDeviceAddress)\n }\n\n return this.fromEncodedStructure(map)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { typedMap } from '../../utils'\n\nenum NfcOptionsKeys {\n MaxCommandDataLength = 0,\n MaxResponseDataLength = 1,\n}\n\n// NfcOptions uses integer keys per spec:\n// NfcOptions = {\n// 0 : uint, // Max command data length\n// 1 : uint // Max response data length\n// }\nconst nfcOptionsSchema = typedMap([\n [NfcOptionsKeys.MaxCommandDataLength, z.number()],\n [NfcOptionsKeys.MaxResponseDataLength, z.number()],\n] as const)\n\nexport type NfcOptionsEncodedStructure = z.input<typeof nfcOptionsSchema>\nexport type NfcOptionsDecodedStructure = z.output<typeof nfcOptionsSchema>\n\nexport type NfcOptionsOptions = {\n maxCommandDataLength: number\n maxResponseDataLength: number\n}\n\nexport class NfcOptions extends CborStructure<NfcOptionsEncodedStructure, NfcOptionsDecodedStructure> {\n public static override get encodingSchema() {\n return nfcOptionsSchema\n }\n\n public get maxCommandDataLength() {\n return this.structure.get(NfcOptionsKeys.MaxCommandDataLength)\n }\n\n public get maxResponseDataLength() {\n return this.structure.get(NfcOptionsKeys.MaxResponseDataLength)\n }\n\n public static create(options: NfcOptionsOptions): NfcOptions {\n const map = new Map([\n [NfcOptionsKeys.MaxCommandDataLength, options.maxCommandDataLength],\n [NfcOptionsKeys.MaxResponseDataLength, options.maxResponseDataLength],\n ])\n\n return this.fromEncodedStructure(map)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { typedMap } from '../../utils'\nimport { zUint8Array } from '../../utils/zod'\n\nenum WifiOptionsKeys {\n Passphrase = 0,\n OperatingClass = 1,\n ChannelNumber = 2,\n SupportedBands = 3,\n}\n\n// WifiOptions uses integer keys per spec:\n// WifiOptions = {\n// ? 0: tstr, // Pass-phrase\n// ? 1: uint, // Operating Class\n// ? 2: uint, // Channel Number\n// ? 3: bstr // Supported Bands\n// }\nconst wifiOptionsSchema = typedMap([\n [WifiOptionsKeys.Passphrase, z.string().exactOptional()],\n [WifiOptionsKeys.OperatingClass, z.number().exactOptional()],\n [WifiOptionsKeys.ChannelNumber, z.number().exactOptional()],\n [WifiOptionsKeys.SupportedBands, zUint8Array.exactOptional()],\n] as const)\n\nexport type WifiOptionsEncodedStructure = z.input<typeof wifiOptionsSchema>\nexport type WifiOptionsDecodedStructure = z.output<typeof wifiOptionsSchema>\n\nexport type WifiOptionsOptions = {\n passphrase?: string\n channelInfoOperatingClass?: number\n channelInfoChannelNumber?: number\n bandInfoSupportedBands?: Uint8Array\n}\n\nexport class WifiOptions extends CborStructure<WifiOptionsEncodedStructure, WifiOptionsDecodedStructure> {\n public static override get encodingSchema() {\n return wifiOptionsSchema\n }\n\n public get encodedStructure() {\n return this.structure.toMap() as WifiOptionsEncodedStructure\n }\n\n public get passphrase() {\n return this.structure.get(WifiOptionsKeys.Passphrase)\n }\n\n public get channelInfoOperatingClass() {\n return this.structure.get(WifiOptionsKeys.OperatingClass)\n }\n\n public get channelInfoChannelNumber() {\n return this.structure.get(WifiOptionsKeys.ChannelNumber)\n }\n\n public get bandInfoSupportedBands() {\n return this.structure.get(WifiOptionsKeys.SupportedBands)\n }\n\n public static create(options: WifiOptionsOptions): WifiOptions {\n const entries: Array<[number, unknown]> = []\n\n if (options.passphrase !== undefined) {\n entries.push([WifiOptionsKeys.Passphrase, options.passphrase])\n }\n\n if (options.channelInfoOperatingClass !== undefined) {\n entries.push([WifiOptionsKeys.OperatingClass, options.channelInfoOperatingClass])\n }\n\n if (options.channelInfoChannelNumber !== undefined) {\n entries.push([WifiOptionsKeys.ChannelNumber, options.channelInfoChannelNumber])\n }\n\n if (options.bandInfoSupportedBands !== undefined) {\n entries.push([WifiOptionsKeys.SupportedBands, options.bandInfoSupportedBands])\n }\n\n const map = new Map(entries)\n return this.fromEncodedStructure(map)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { BleOptions, type BleOptionsEncodedStructure } from './ble-options'\nimport { NfcOptions, type NfcOptionsEncodedStructure } from './nfc-options'\nimport type { RetrievalOptions } from './retrieval-options'\nimport { WifiOptions, type WifiOptionsEncodedStructure } from './wifi-options'\n\nexport enum DeviceRetrievalMethodType {\n Nfc = 1,\n Ble = 2,\n WifiAware = 3,\n}\n\nconst deviceRetrievalMethodEncodedSchema = z.tuple([\n z.enum(DeviceRetrievalMethodType).or(z.number()),\n z.number(),\n z.map(z.unknown(), z.unknown()),\n])\n\nconst deviceRetrievalMethodDecodedSchema = z.object({\n // Parsing should not fail if one unknown device retrieval method is included\n type: z.enum(DeviceRetrievalMethodType).or(z.number()),\n version: z.number(),\n retrievalOptions: z.union([\n z.instanceof(NfcOptions),\n z.instanceof(BleOptions),\n z.instanceof(WifiOptions),\n // Parsing should not fail if one unknown device retrieval method is included\n z.map(z.unknown(), z.unknown()),\n ]),\n})\n\nexport type DeviceRetrievalMethodEncodedStructure = z.infer<typeof deviceRetrievalMethodEncodedSchema>\nexport type DeviceRetrievalMethodDecodedStructure = z.infer<typeof deviceRetrievalMethodDecodedSchema>\n\nexport type DeviceRetrievalMethodOptions = {\n type: DeviceRetrievalMethodType | number\n version: number\n retrievalOptions: RetrievalOptions\n}\n\nexport class DeviceRetrievalMethod extends CborStructure<\n DeviceRetrievalMethodEncodedStructure,\n DeviceRetrievalMethodDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(deviceRetrievalMethodEncodedSchema, deviceRetrievalMethodDecodedSchema, {\n decode: ([type, version, retrievalOptions]) => {\n let options: RetrievalOptions | Map<unknown, unknown>\n\n if (type === DeviceRetrievalMethodType.Nfc) {\n options = NfcOptions.fromEncodedStructure(retrievalOptions as NfcOptionsEncodedStructure)\n } else if (type === DeviceRetrievalMethodType.Ble) {\n options = BleOptions.fromEncodedStructure(retrievalOptions as BleOptionsEncodedStructure)\n } else if (type === DeviceRetrievalMethodType.WifiAware) {\n options = WifiOptions.fromEncodedStructure(retrievalOptions as WifiOptionsEncodedStructure)\n } else {\n // Unknown type\n options = retrievalOptions\n }\n\n return {\n type,\n version,\n retrievalOptions: options,\n }\n },\n encode: ({ type, version, retrievalOptions }) =>\n [\n type,\n version,\n retrievalOptions instanceof CborStructure ? retrievalOptions.encodedStructure : retrievalOptions,\n ] satisfies DeviceRetrievalMethodEncodedStructure,\n })\n }\n\n public get type() {\n return this.structure.type\n }\n\n public get version() {\n return this.structure.version\n }\n\n public get retrievalOptions() {\n return this.structure.retrievalOptions\n }\n\n public static create(options: DeviceRetrievalMethodOptions): DeviceRetrievalMethod {\n return this.fromDecodedStructure({\n type: options.type,\n version: options.version,\n retrievalOptions: options.retrievalOptions,\n })\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor'\n\nconst protocolInfoSchema = z.unknown()\nexport type ProtocolInfoStructure = z.infer<typeof protocolInfoSchema>\n\nexport class ProtocolInfo extends CborStructure<ProtocolInfoStructure> {\n public static override get encodingSchema() {\n return protocolInfoSchema\n }\n}\n","import {\n CoseKey,\n type CoseKeyDecodedStructure,\n type CoseKeyEncodedStructure,\n type CoseKeyOptions,\n} from '../../cose/key/key'\n\nexport type EDeviceKeyDecodedStructure = CoseKeyDecodedStructure\nexport type EDeviceKeyEncodedStructure = CoseKeyEncodedStructure\nexport type EDeviceKeyOptions = CoseKeyOptions\n\nexport class EDeviceKey extends CoseKey {}\n","import { z } from 'zod'\nimport { CborStructure, DataItem } from '../../cbor'\nimport { EDeviceKey } from './e-device-key'\n\nconst securityEncodedSchema = z.tuple([z.number(), z.instanceof(DataItem)])\n\nconst securityDecodedSchema = z.object({\n cipherSuiteIdentifier: z.number(),\n eDeviceKey: z.instanceof(EDeviceKey),\n})\n\nexport type SecurityEncodedStructure = z.infer<typeof securityEncodedSchema>\nexport type SecurityDecodedStructure = z.infer<typeof securityDecodedSchema>\n\nexport type SecurityOptions = {\n cipherSuiteIdentifier: number\n eDeviceKey: EDeviceKey\n}\n\nexport class Security extends CborStructure<SecurityEncodedStructure, SecurityDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(securityEncodedSchema, securityDecodedSchema, {\n decode: (input) => ({\n cipherSuiteIdentifier: input[0],\n // biome-ignore lint/suspicious/noExplicitAny: CoseKey encoded structure\n eDeviceKey: EDeviceKey.fromEncodedStructure((input[1] as DataItem).data as any),\n }),\n encode: (output): SecurityEncodedStructure => [\n output.cipherSuiteIdentifier,\n DataItem.fromData(output.eDeviceKey.encodedStructure),\n ],\n })\n }\n\n public get cipherSuiteIdentifier() {\n return this.structure.cipherSuiteIdentifier\n }\n\n public get eDeviceKey() {\n return this.structure.eDeviceKey\n }\n\n public static create(options: SecurityOptions): Security {\n return this.fromDecodedStructure({\n cipherSuiteIdentifier: options.cipherSuiteIdentifier,\n eDeviceKey: options.eDeviceKey,\n })\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\n\n// Oidc = [uint, tstr, tstr] - Array structure\nconst oidcEncodedSchema = z.tuple([z.number(), z.string(), z.string()])\n\n// Easier structure for internal usage in class\nconst oidcDecodedSchema = z.object({\n version: z.number(),\n issuerUrl: z.string(),\n serverRetrievalToken: z.string(),\n})\n\nexport type OidcEncodedStructure = z.infer<typeof oidcEncodedSchema>\nexport type OidcDecodedStructure = z.infer<typeof oidcDecodedSchema>\nexport type OidcOptions = OidcDecodedStructure\n\nexport class Oidc extends CborStructure<OidcEncodedStructure, OidcDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(oidcEncodedSchema, oidcDecodedSchema, {\n decode: ([version, issuerUrl, serverRetrievalToken]) => ({\n version,\n issuerUrl,\n serverRetrievalToken,\n }),\n encode: ({ version, issuerUrl, serverRetrievalToken }) =>\n [version, issuerUrl, serverRetrievalToken] satisfies OidcEncodedStructure,\n })\n }\n\n public get version() {\n return this.structure.version\n }\n\n public get issuerUrl() {\n return this.structure.issuerUrl\n }\n\n public get serverRetrievalToken() {\n return this.structure.serverRetrievalToken\n }\n\n public static create(options: OidcOptions): Oidc {\n return new Oidc({\n version: options.version,\n issuerUrl: options.issuerUrl,\n serverRetrievalToken: options.serverRetrievalToken,\n })\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\n\n// WebApi = [uint, tstr, tstr] - Array structure\nconst webApiEncodedSchema = z.tuple([z.number(), z.string(), z.string()])\n\n// Easier structure for internal usage in class\nconst webApiDecodedSchema = z.object({\n version: z.number(),\n issuerUrl: z.string(),\n serverRetrievalToken: z.string(),\n})\n\nexport type WebApiEncodedStructure = z.infer<typeof webApiEncodedSchema>\nexport type WebApiDecodedStructure = z.infer<typeof webApiDecodedSchema>\nexport type WebApiOptions = WebApiDecodedStructure\n\nexport class WebApi extends CborStructure<WebApiEncodedStructure, WebApiDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(webApiEncodedSchema, webApiDecodedSchema, {\n encode: ({ version, issuerUrl, serverRetrievalToken }) =>\n [version, issuerUrl, serverRetrievalToken] satisfies WebApiEncodedStructure,\n decode: ([version, issuerUrl, serverRetrievalToken]) => ({\n version,\n issuerUrl,\n serverRetrievalToken,\n }),\n })\n }\n\n public get version() {\n return this.structure.version\n }\n\n public get issuerUrl() {\n return this.structure.issuerUrl\n }\n\n public get serverRetrievalToken() {\n return this.structure.serverRetrievalToken\n }\n\n public static create(options: WebApiOptions): WebApi {\n return this.fromDecodedStructure(options)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { TypedMap, typedMap } from '../../utils'\nimport { Oidc, type OidcEncodedStructure } from './oidc'\nimport { WebApi, type WebApiEncodedStructure } from './web-api'\n\nconst serverRetrievalMethodSchema = typedMap([\n ['webApi', z.instanceof(WebApi).exactOptional()],\n ['oidc', z.instanceof(Oidc).exactOptional()],\n] as const)\n\nexport type ServerRetrievalMethodDecodedStructure = z.output<typeof serverRetrievalMethodSchema>\nexport type ServerRetrievalMethodEncodedStructure = z.input<typeof serverRetrievalMethodSchema>\n\nexport type ServerRetrievalMethodOptions = {\n webApi?: WebApi\n oidc?: Oidc\n}\n\nexport class ServerRetrievalMethod extends CborStructure<\n ServerRetrievalMethodEncodedStructure,\n ServerRetrievalMethodDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(serverRetrievalMethodSchema.in, serverRetrievalMethodSchema.out, {\n decode: (input) => {\n const map: ServerRetrievalMethodDecodedStructure = TypedMap.fromMap(input)\n\n if (input.has('webApi')) {\n map.set('webApi', WebApi.fromEncodedStructure(input.get('webApi') as WebApiEncodedStructure))\n }\n if (input.has('oidc')) {\n map.set('oidc', Oidc.fromEncodedStructure(input.get('oidc') as OidcEncodedStructure))\n }\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n const webApi = output.get('webApi')\n if (webApi) {\n map.set('webApi', webApi.encodedStructure)\n }\n const oidc = output.get('oidc')\n if (oidc) {\n map.set('oidc', oidc.encodedStructure)\n }\n return map\n },\n })\n }\n\n public get webApi() {\n return this.structure.get('webApi')\n }\n\n public get oidc() {\n return this.structure.get('oidc')\n }\n\n public static create(options: ServerRetrievalMethodOptions): ServerRetrievalMethod {\n const map: ServerRetrievalMethodDecodedStructure = new TypedMap([])\n if (options.webApi) {\n map.set('webApi', options.webApi)\n }\n if (options.oidc) {\n map.set('oidc', options.oidc)\n }\n return this.fromDecodedStructure(map)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { TypedMap, typedMap } from '../../utils'\nimport { DeviceRetrievalMethod, type DeviceRetrievalMethodEncodedStructure } from './device-retrieval-method'\nimport { ProtocolInfo, type ProtocolInfoStructure } from './protocol-info'\nimport { Security, type SecurityEncodedStructure } from './security'\nimport { ServerRetrievalMethod, type ServerRetrievalMethodEncodedStructure } from './server-retrieval-method'\n\nenum DeviceEngagementKeys {\n Version = 0,\n Security = 1,\n DeviceRetrievalMethods = 2,\n ServerRetrievalMethods = 3,\n ProtocolInfo = 4,\n}\n\nconst deviceEngagementSchema = typedMap([\n [DeviceEngagementKeys.Version, z.string()],\n [DeviceEngagementKeys.Security, z.instanceof(Security)],\n [DeviceEngagementKeys.DeviceRetrievalMethods, z.array(z.instanceof(DeviceRetrievalMethod)).exactOptional()],\n [DeviceEngagementKeys.ServerRetrievalMethods, z.array(z.instanceof(ServerRetrievalMethod)).exactOptional()],\n [DeviceEngagementKeys.ProtocolInfo, z.instanceof(ProtocolInfo).exactOptional()],\n] as const)\n\nexport type DeviceEngagementEncodedStructure = z.input<typeof deviceEngagementSchema>\nexport type DeviceEngagementDecodedStructure = z.output<typeof deviceEngagementSchema>\n\nexport type DeviceEngagementOptions = {\n version: string\n security: Security\n deviceRetrievalMethods?: Array<DeviceRetrievalMethod>\n serverRetrievalMethods?: Array<ServerRetrievalMethod>\n protocolInfo?: ProtocolInfo\n}\n\nexport class DeviceEngagement extends CborStructure<\n DeviceEngagementEncodedStructure,\n DeviceEngagementDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(deviceEngagementSchema.in, deviceEngagementSchema.out, {\n decode: (input) => {\n const map: DeviceEngagementDecodedStructure = TypedMap.fromMap(input)\n\n map.set(\n DeviceEngagementKeys.Security,\n Security.fromEncodedStructure(input.get(DeviceEngagementKeys.Security) as SecurityEncodedStructure)\n )\n\n if (input.has(DeviceEngagementKeys.DeviceRetrievalMethods)) {\n const deviceMethods = input.get(\n DeviceEngagementKeys.DeviceRetrievalMethods\n ) as DeviceRetrievalMethodEncodedStructure[]\n map.set(\n DeviceEngagementKeys.DeviceRetrievalMethods,\n deviceMethods.map((encoded) => DeviceRetrievalMethod.fromEncodedStructure(encoded))\n )\n }\n\n if (input.has(DeviceEngagementKeys.ServerRetrievalMethods)) {\n const serverMethods = input.get(\n DeviceEngagementKeys.ServerRetrievalMethods\n ) as ServerRetrievalMethodEncodedStructure[]\n map.set(\n DeviceEngagementKeys.ServerRetrievalMethods,\n serverMethods.map((encoded) => ServerRetrievalMethod.fromEncodedStructure(encoded))\n )\n }\n\n if (input.has(DeviceEngagementKeys.ProtocolInfo)) {\n map.set(\n DeviceEngagementKeys.ProtocolInfo,\n ProtocolInfo.fromEncodedStructure(input.get(DeviceEngagementKeys.ProtocolInfo) as ProtocolInfoStructure)\n )\n }\n\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n\n map.set(DeviceEngagementKeys.Security, output.get(DeviceEngagementKeys.Security).encodedStructure)\n\n const deviceRetrievalMethods = output.get(DeviceEngagementKeys.DeviceRetrievalMethods)\n if (deviceRetrievalMethods) {\n map.set(\n DeviceEngagementKeys.DeviceRetrievalMethods,\n deviceRetrievalMethods.map((drm) => drm.encodedStructure)\n )\n }\n\n const serverRetrievalMethods = output.get(DeviceEngagementKeys.ServerRetrievalMethods)\n if (serverRetrievalMethods) {\n map.set(\n DeviceEngagementKeys.ServerRetrievalMethods,\n serverRetrievalMethods.map((srm) => srm.encodedStructure)\n )\n }\n\n const protocolInfo = output.get(DeviceEngagementKeys.ProtocolInfo)\n if (protocolInfo) {\n map.set(DeviceEngagementKeys.ProtocolInfo, protocolInfo.encodedStructure)\n }\n\n return map\n },\n })\n }\n\n public get version() {\n return this.structure.get(DeviceEngagementKeys.Version)\n }\n\n public get security() {\n return this.structure.get(DeviceEngagementKeys.Security)\n }\n\n public get deviceRetrievalMethods() {\n return this.structure.get(DeviceEngagementKeys.DeviceRetrievalMethods)\n }\n\n public get serverRetrievalMethods() {\n return this.structure.get(DeviceEngagementKeys.ServerRetrievalMethods)\n }\n\n public get protocolInfo() {\n return this.structure.get(DeviceEngagementKeys.ProtocolInfo)\n }\n\n public static create(options: DeviceEngagementOptions): DeviceEngagement {\n const map = new Map<number, unknown>([\n [DeviceEngagementKeys.Version, options.version],\n [DeviceEngagementKeys.Security, options.security],\n ])\n\n if (options.deviceRetrievalMethods !== undefined) {\n map.set(DeviceEngagementKeys.DeviceRetrievalMethods, options.deviceRetrievalMethods)\n }\n\n if (options.serverRetrievalMethods !== undefined) {\n map.set(DeviceEngagementKeys.ServerRetrievalMethods, options.serverRetrievalMethods)\n }\n\n if (options.protocolInfo !== undefined) {\n map.set(DeviceEngagementKeys.ProtocolInfo, options.protocolInfo)\n }\n\n return this.fromEncodedStructure(map)\n }\n}\n","import {\n CoseKey,\n type CoseKeyDecodedStructure,\n type CoseKeyEncodedStructure,\n type CoseKeyOptions,\n} from '../../cose/key/key'\n\nexport type EReaderKeyDecodedStructure = CoseKeyDecodedStructure\nexport type EReaderKeyEncodedStructure = CoseKeyEncodedStructure\nexport type EReaderKeyOptions = CoseKeyOptions\n\n// EReaderKey is just a CoseKey with a different name/type for clarity in mdoc context\nexport class EReaderKey extends CoseKey {}\n","import { CborStructure, type DecodedStructureType, type EncodedStructureType } from '../../cbor'\n\nexport abstract class Handover<EncodedStructure = unknown, DecodedStructure = EncodedStructure> extends CborStructure<\n EncodedStructure,\n DecodedStructure\n> {\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n public static tryDecodeHandover<T extends Handover<any, any>>(\n this: {\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n new (structure: any): T\n fromEncodedStructure: (encodedStructure: EncodedStructureType<T>) => { decodedStructure: DecodedStructureType<T> }\n },\n structure: unknown\n ): T | null {\n try {\n // May feel weird, but using new this makes TypeScript understand we may return a subclass\n return new this(this.fromEncodedStructure(structure as EncodedStructureType<T>).decodedStructure)\n } catch {\n // We just return null if the parsing fails\n return null\n }\n }\n\n /**\n * Whether this handover structure requires a reader key. Can\n * be overridden in extending handover classes.\n */\n public get requiresReaderKey() {\n return false\n }\n\n /**\n * Whether this handover structure requires device engagement structure. Can\n * be overridden in extending handover classes.\n */\n public get requiresDeviceEngagement() {\n return false\n }\n}\n","import z from 'zod'\nimport { zUint8Array } from '../../utils/zod'\nimport { Handover } from './handover'\n\nconst nfcHandoverEncodedSchema = z.tuple([zUint8Array, zUint8Array.nullable()])\nconst nfcHandoverDecodedSchema = z.object({\n selectMessage: zUint8Array,\n requestMessage: zUint8Array.nullable(),\n})\n\nexport type NfcHandoverEncodedStructure = z.infer<typeof nfcHandoverEncodedSchema>\nexport type NfcHandoverDecodedStructure = z.infer<typeof nfcHandoverDecodedSchema>\n\nexport type NfcHandoverOptions = {\n selectMessage: Uint8Array\n requestMessage?: Uint8Array\n}\n\nexport class NfcHandover extends Handover<NfcHandoverEncodedStructure, NfcHandoverDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(nfcHandoverEncodedSchema, nfcHandoverDecodedSchema, {\n encode: ({ selectMessage, requestMessage }) =>\n [selectMessage, requestMessage] satisfies NfcHandoverEncodedStructure,\n decode: ([selectMessage, requestMessage]) => ({ selectMessage, requestMessage }),\n })\n }\n\n public get selectMessage() {\n return this.structure.selectMessage\n }\n\n public get requestMessage() {\n return this.structure.requestMessage\n }\n\n public static create(options: NfcHandoverOptions) {\n return this.fromDecodedStructure({\n requestMessage: options.requestMessage ?? null,\n selectMessage: options.selectMessage,\n })\n }\n\n public override get requiresReaderKey() {\n return true\n }\n\n public override get requiresDeviceEngagement() {\n return true\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor'\n\nconst oid4vpDcApiDraft24HandoverInfoSchema = z.tuple([z.string(), z.string(), z.string()])\nconst oid4vpDcApiDraft24HandoverInfoDecodedSchema = z.object({\n origin: z.string(),\n clientId: z.string(),\n nonce: z.string(),\n})\n\nexport type Oid4vpDcApiDraft24HandoverInfoEncodedStructure = z.infer<typeof oid4vpDcApiDraft24HandoverInfoSchema>\nexport type Oid4vpDcApiDraft24HandoverInfoDecodedStructure = z.infer<typeof oid4vpDcApiDraft24HandoverInfoDecodedSchema>\n\nexport type Oid4vpDcApiDraft24HandoverInfoOptions = {\n origin: string\n clientId: string\n nonce: string\n}\n\nexport class Oid4vpDcApiDraft24HandoverInfo extends CborStructure<\n Oid4vpDcApiDraft24HandoverInfoEncodedStructure,\n Oid4vpDcApiDraft24HandoverInfoDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(oid4vpDcApiDraft24HandoverInfoSchema, oid4vpDcApiDraft24HandoverInfoDecodedSchema, {\n encode: ({ origin, clientId, nonce }) =>\n [origin, clientId, nonce] satisfies Oid4vpDcApiDraft24HandoverInfoEncodedStructure,\n decode: ([origin, clientId, nonce]) => ({ origin, clientId, nonce }),\n })\n }\n\n public get origin() {\n return this.structure.origin\n }\n\n public get clientId() {\n return this.structure.clientId\n }\n\n public get nonce() {\n return this.structure.nonce\n }\n\n public static create(options: Oid4vpDcApiDraft24HandoverInfoOptions) {\n return this.fromDecodedStructure({\n origin: options.origin,\n clientId: options.clientId,\n nonce: options.nonce,\n })\n }\n}\n","import z from 'zod'\nimport type { MdocContext } from '../../context'\nimport { zUint8Array } from '../../utils/zod'\nimport { Handover } from './handover'\nimport type { Oid4vpDcApiDraft24HandoverInfo } from './oid4vp-dc-api-draft24-handover-info'\nimport type { Oid4vpDcApiHandoverInfo } from './oid4vp-dc-api-handover-info'\n\nconst oid4vpDcApiHandoverEncodedSchema = z.tuple([z.literal('OpenID4VPDCAPIHandover'), zUint8Array])\nconst oid4vpDcApiHandoverDecodedSchema = zUint8Array\n\nexport type Oid4vpDcApiHandoverEncodedStructure = z.infer<typeof oid4vpDcApiHandoverEncodedSchema>\nexport type Oid4vpDcApiHandoverDecodedStructure = z.infer<typeof oid4vpDcApiHandoverDecodedSchema>\n\nexport type Oid4vpDcApiHandoverOptions = {\n oid4vpDcApiHandoverInfo: Oid4vpDcApiHandoverInfo | Oid4vpDcApiDraft24HandoverInfo\n}\n\nexport class Oid4vpDcApiHandover extends Handover<\n Oid4vpDcApiHandoverEncodedStructure,\n Oid4vpDcApiHandoverDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(oid4vpDcApiHandoverEncodedSchema, oid4vpDcApiHandoverDecodedSchema, {\n encode: (handoverInfoHash) =>\n ['OpenID4VPDCAPIHandover', handoverInfoHash] satisfies Oid4vpDcApiHandoverEncodedStructure,\n decode: ([, handoverInfoHash]) => handoverInfoHash,\n })\n }\n\n public static createFromHash(oid4vpDcApiHandoverInfoHash: Uint8Array) {\n return this.fromDecodedStructure(oid4vpDcApiHandoverInfoHash)\n }\n\n public static async create(options: Oid4vpDcApiHandoverOptions, ctx: Pick<MdocContext, 'crypto'>) {\n const oid4vpDcApiHandoverInfoHash = await ctx.crypto.digest({\n digestAlgorithm: 'SHA-256',\n bytes: options.oid4vpDcApiHandoverInfo.encode(),\n })\n\n return this.fromDecodedStructure(oid4vpDcApiHandoverInfoHash)\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { zUint8Array } from '../../utils/zod'\n\nconst oid4vpDcApiHandoverInfoEncodedSchema = z.tuple([z.string(), z.string(), zUint8Array.nullable()])\nconst oid4vpDcApiHandoverInfoDecodedSchema = z.object({\n origin: z.string(),\n nonce: z.string(),\n jwkThumbprint: zUint8Array.nullable(),\n})\n\nexport type Oid4vpDcApiHandoverInfoEncodedStructure = z.infer<typeof oid4vpDcApiHandoverInfoEncodedSchema>\nexport type Oid4vpDcApiHandoverInfoDecodedStructure = z.infer<typeof oid4vpDcApiHandoverInfoDecodedSchema>\n\nexport type Oid4vpDcApiHandoverInfoOptions = {\n origin: string\n nonce: string\n jwkThumbprint?: Uint8Array\n}\n\nexport class Oid4vpDcApiHandoverInfo extends CborStructure<\n Oid4vpDcApiHandoverInfoEncodedStructure,\n Oid4vpDcApiHandoverInfoDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(oid4vpDcApiHandoverInfoEncodedSchema, oid4vpDcApiHandoverInfoDecodedSchema, {\n encode: ({ origin, nonce, jwkThumbprint }) =>\n [origin, nonce, jwkThumbprint] satisfies Oid4vpDcApiHandoverInfoEncodedStructure,\n decode: ([origin, nonce, jwkThumbprint]) => ({ origin, nonce, jwkThumbprint }),\n })\n }\n\n public get origin() {\n return this.structure.origin\n }\n\n public get nonce() {\n return this.structure.nonce\n }\n\n public get jwkThumbprint() {\n return this.structure.jwkThumbprint\n }\n\n public static create(options: Oid4vpDcApiHandoverInfoOptions) {\n return this.fromDecodedStructure({\n origin: options.origin,\n nonce: options.nonce,\n jwkThumbprint: options.jwkThumbprint ?? null,\n })\n }\n}\n","import z from 'zod'\nimport { cborEncode } from '../../cbor'\nimport type { MdocContext } from '../../context'\nimport { zUint8Array } from '../../utils/zod'\nimport { Handover } from './handover'\n\nconst oid4vpDraft18HandoverEncodedSchema = z.tuple([zUint8Array, zUint8Array, z.string()])\nconst oid4vpDraft18HandoverDecodedSchema = z.object({\n clientIdHash: zUint8Array,\n responseUriHash: zUint8Array,\n nonce: z.string(),\n})\n\nexport type Oid4vpDraft18HandoverEncodedStructure = z.infer<typeof oid4vpDraft18HandoverEncodedSchema>\nexport type Oid4vpDraft18HandoverDecodedStructure = z.infer<typeof oid4vpDraft18HandoverDecodedSchema>\n\nexport type Oid4vpDraft18HandoverOptions = {\n clientId: string\n responseUri: string\n mdocGeneratedNonce: string\n nonce: string\n}\n\nexport class Oid4vpDraft18Handover extends Handover<\n Oid4vpDraft18HandoverEncodedStructure,\n Oid4vpDraft18HandoverDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(oid4vpDraft18HandoverEncodedSchema, oid4vpDraft18HandoverDecodedSchema, {\n encode: ({ clientIdHash, responseUriHash, nonce }) =>\n [clientIdHash, responseUriHash, nonce] satisfies Oid4vpDraft18HandoverEncodedStructure,\n decode: ([clientIdHash, responseUriHash, nonce]) => ({ clientIdHash, responseUriHash, nonce }),\n })\n }\n\n public static async create(options: Oid4vpDraft18HandoverOptions, ctx: Pick<MdocContext, 'crypto'>) {\n const clientIdHash = await ctx.crypto.digest({\n digestAlgorithm: 'SHA-256',\n bytes: cborEncode([options.clientId, options.mdocGeneratedNonce]),\n })\n\n const responseUriHash = await ctx.crypto.digest({\n digestAlgorithm: 'SHA-256',\n bytes: cborEncode([options.responseUri, options.mdocGeneratedNonce]),\n })\n\n return this.fromDecodedStructure({\n clientIdHash,\n responseUriHash,\n nonce: options.nonce,\n })\n }\n}\n","import z from 'zod'\nimport type { MdocContext } from '../../context'\nimport { zUint8Array } from '../../utils/zod'\nimport { Handover } from './handover'\nimport type { Oid4vpHandoverInfo } from './oid4vp-handover-info'\n\nconst oid4vpHandoverEncodedSchema = z.tuple([z.literal('OpenID4VPHandover'), zUint8Array])\nconst oid4vpHandoverDecodedSchema = zUint8Array\n\nexport type Oid4vpHandoverEncodedStructure = z.infer<typeof oid4vpHandoverEncodedSchema>\nexport type Oid4vpHandoverDecodedStructure = z.infer<typeof oid4vpHandoverDecodedSchema>\n\nexport type Oid4vpHandoverOptions = {\n oid4vpHandoverInfo: Oid4vpHandoverInfo\n}\n\nexport class Oid4vpHandover extends Handover<Oid4vpHandoverEncodedStructure, Oid4vpHandoverDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(oid4vpHandoverEncodedSchema, oid4vpHandoverDecodedSchema, {\n encode: (handoverInfoHash) => ['OpenID4VPHandover', handoverInfoHash] satisfies Oid4vpHandoverEncodedStructure,\n decode: ([, handoverInfoHash]) => handoverInfoHash,\n })\n }\n\n public get handoverInfoHash() {\n return this.structure\n }\n\n public static createFromHash(oid4vpHandoverInfoHash: Uint8Array) {\n return this.fromDecodedStructure(oid4vpHandoverInfoHash)\n }\n\n public static async create(options: Oid4vpHandoverOptions, ctx: Pick<MdocContext, 'crypto'>) {\n const oid4vpHandoverInfoHash = await ctx.crypto.digest({\n digestAlgorithm: 'SHA-256',\n bytes: options.oid4vpHandoverInfo.encode(),\n })\n\n return this.fromDecodedStructure(oid4vpHandoverInfoHash)\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { zUint8Array } from '../../utils/zod'\n\nconst oid4vpHandoverInfoEncodedSchema = z.tuple([z.string(), z.string(), zUint8Array.nullable(), z.string()])\nconst oid4vpHandoverInfoDecodedSchema = z.object({\n clientId: z.string(),\n nonce: z.string(),\n jwkThumbprint: zUint8Array.nullable(),\n responseUri: z.string(),\n})\n\nexport type Oid4vpHandoverInfoEncodedStructure = z.infer<typeof oid4vpHandoverInfoEncodedSchema>\nexport type Oid4vpHandoverInfoDecodedStructure = z.infer<typeof oid4vpHandoverInfoDecodedSchema>\n\nexport type Oid4vpHandoverInfoOptions = {\n clientId: string\n nonce: string\n jwkThumbprint?: Uint8Array\n responseUri: string\n}\n\nexport class Oid4vpHandoverInfo extends CborStructure<\n Oid4vpHandoverInfoEncodedStructure,\n Oid4vpHandoverInfoDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(oid4vpHandoverInfoEncodedSchema, oid4vpHandoverInfoDecodedSchema, {\n encode: ({ clientId, nonce, jwkThumbprint, responseUri }) =>\n [clientId, nonce, jwkThumbprint, responseUri] satisfies Oid4vpHandoverInfoEncodedStructure,\n decode: ([clientId, nonce, jwkThumbprint, responseUri]) => ({ clientId, nonce, jwkThumbprint, responseUri }),\n })\n }\n\n public get clientId() {\n return this.structure.clientId\n }\n\n public get nonce() {\n return this.structure.nonce\n }\n\n public get jwkThumbprint() {\n return this.structure.jwkThumbprint\n }\n\n public get responseUri() {\n return this.structure.responseUri\n }\n\n public static create(options: Oid4vpHandoverInfoOptions) {\n return this.fromDecodedStructure({\n clientId: options.clientId,\n nonce: options.nonce,\n jwkThumbprint: options.jwkThumbprint ?? null,\n responseUri: options.responseUri,\n })\n }\n}\n","import z from 'zod'\nimport type { MdocContext } from '../../context'\nimport { zUint8Array } from '../../utils/zod'\nimport { Handover } from './handover'\nimport type { Oid4vpIaeHandoverInfo } from './oid4vp-iae-handover-info'\n\nconst oid4vpIaeHandoverEncodedSchema = z.tuple([z.literal('OpenID4VCIIAEHandover'), zUint8Array])\nconst oid4vpIaeHandoverDecodedSchema = zUint8Array\n\nexport type Oid4vpIaeHandoverEncodedStructure = z.infer<typeof oid4vpIaeHandoverEncodedSchema>\nexport type Oid4vpIaeHandoverDecodedStructure = z.infer<typeof oid4vpIaeHandoverDecodedSchema>\n\nexport type Oid4vpIaeHandoverOptions = {\n oid4vpIaeHandoverInfo: Oid4vpIaeHandoverInfo\n}\n\nexport class Oid4vpIaeHandover extends Handover<Oid4vpIaeHandoverEncodedStructure, Oid4vpIaeHandoverDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(oid4vpIaeHandoverEncodedSchema, oid4vpIaeHandoverDecodedSchema, {\n encode: (handoverInfoHash) =>\n ['OpenID4VCIIAEHandover', handoverInfoHash] satisfies Oid4vpIaeHandoverEncodedStructure,\n decode: ([, handoverInfoHash]) => handoverInfoHash,\n })\n }\n\n public static createFromHash(oid4vpIaeHandoverInfoHash: Uint8Array) {\n return this.fromDecodedStructure(oid4vpIaeHandoverInfoHash)\n }\n\n public static async create(options: Oid4vpIaeHandoverOptions, ctx: Pick<MdocContext, 'crypto'>) {\n const oid4vpIaeHandoverInfoHash = await ctx.crypto.digest({\n digestAlgorithm: 'SHA-256',\n bytes: options.oid4vpIaeHandoverInfo.encode(),\n })\n\n return this.fromDecodedStructure(oid4vpIaeHandoverInfoHash)\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { zUint8Array } from '../../utils/zod'\n\nconst oid4vpIaeHandoverInfoEncodedSchema = z.tuple([z.string(), z.string(), zUint8Array.nullable()])\nconst oid4vpIaeHandoverInfoDecodedSchema = z.object({\n interactiveAuthorizationEndpoint: z.string(),\n nonce: z.string(),\n jwkThumbprint: zUint8Array.nullable(),\n})\n\nexport type Oid4vpIaeHandoverInfoEncodedStructure = z.infer<typeof oid4vpIaeHandoverInfoEncodedSchema>\nexport type Oid4vpIaeHandoverInfoDecodedStructure = z.infer<typeof oid4vpIaeHandoverInfoDecodedSchema>\n\nexport type Oid4vpIaeHandoverInfoOptions = {\n interactiveAuthorizationEndpoint: string\n nonce: string\n jwkThumbprint?: Uint8Array\n}\n\nexport class Oid4vpIaeHandoverInfo extends CborStructure<\n Oid4vpIaeHandoverInfoEncodedStructure,\n Oid4vpIaeHandoverInfoDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(oid4vpIaeHandoverInfoEncodedSchema, oid4vpIaeHandoverInfoDecodedSchema, {\n encode: ({ interactiveAuthorizationEndpoint, nonce, jwkThumbprint }) =>\n [interactiveAuthorizationEndpoint, nonce, jwkThumbprint] satisfies Oid4vpIaeHandoverInfoEncodedStructure,\n decode: ([interactiveAuthorizationEndpoint, nonce, jwkThumbprint]) => ({\n interactiveAuthorizationEndpoint,\n nonce,\n jwkThumbprint,\n }),\n })\n }\n\n public get interactiveAuthorizationEndpoint() {\n return this.structure.interactiveAuthorizationEndpoint\n }\n\n public get nonce() {\n return this.structure.nonce\n }\n\n public get jwkThumbprint() {\n return this.structure.jwkThumbprint\n }\n\n public static create(options: Oid4vpIaeHandoverInfoOptions) {\n return this.fromDecodedStructure({\n interactiveAuthorizationEndpoint: options.interactiveAuthorizationEndpoint,\n nonce: options.nonce,\n jwkThumbprint: options.jwkThumbprint ?? null,\n })\n }\n}\n","import z from 'zod'\nimport { Handover } from './handover'\n\nconst qrHandoverSchema = z.null()\nexport type QrHandoverStructure = z.infer<typeof qrHandoverSchema>\n\nexport class QrHandover extends Handover<QrHandoverStructure> {\n public static override get encodingSchema() {\n return qrHandoverSchema\n }\n\n public override get requiresReaderKey() {\n return true\n }\n\n public override get requiresDeviceEngagement() {\n return true\n }\n\n public static create() {\n return this.fromDecodedStructure(null)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure, DataItem } from '../../cbor'\nimport type { MdocContext } from '../../context'\nimport { DeviceEngagement, type DeviceEngagementEncodedStructure } from './device-engagement'\nimport { EReaderKey, type EReaderKeyEncodedStructure } from './e-reader-key'\nimport { Handover } from './handover'\nimport { NfcHandover } from './nfc-handover'\nimport {\n Oid4vpDcApiDraft24HandoverInfo,\n type Oid4vpDcApiDraft24HandoverInfoOptions,\n} from './oid4vp-dc-api-draft24-handover-info'\nimport { Oid4vpDcApiHandover } from './oid4vp-dc-api-handover'\nimport { Oid4vpDcApiHandoverInfo, type Oid4vpDcApiHandoverInfoOptions } from './oid4vp-dc-api-handover-info'\nimport { Oid4vpDraft18Handover } from './oid4vp-draft18-handover'\nimport { Oid4vpHandover } from './oid4vp-handover'\nimport { Oid4vpHandoverInfo, type Oid4vpHandoverInfoOptions } from './oid4vp-handover-info'\nimport { Oid4vpIaeHandover } from './oid4vp-iae-handover'\nimport { Oid4vpIaeHandoverInfo, type Oid4vpIaeHandoverInfoOptions } from './oid4vp-iae-handover-info'\nimport { QrHandover } from './qr-handover'\n\nconst supportedHandoverStructures = [\n Oid4vpHandover,\n Oid4vpDcApiHandover,\n Oid4vpIaeHandover,\n NfcHandover,\n QrHandover,\n Oid4vpDraft18Handover,\n] as const\n\nexport const sessionTranscriptEncodedSchema = z.tuple([\n z.instanceof<typeof DataItem<DeviceEngagementEncodedStructure>>(DataItem).nullable(),\n z.instanceof<typeof DataItem<EReaderKeyEncodedStructure>>(DataItem).nullable(),\n z.unknown(),\n])\n\nconst sessionTranscriptDecodedSchema = z.object({\n deviceEngagement: z.instanceof(DeviceEngagement).nullable(),\n eReaderKey: z.instanceof(EReaderKey).nullable(),\n handover: z.instanceof(Handover),\n})\n\nexport type SessionTranscriptDecodedStructure = z.infer<typeof sessionTranscriptDecodedSchema>\nexport type SessionTranscriptEncodedStructure = z.infer<typeof sessionTranscriptEncodedSchema>\n\nexport type SessionTranscriptOptions = {\n deviceEngagement?: DeviceEngagement\n eReaderKey?: EReaderKey\n handover: Handover\n}\n\nexport class SessionTranscript extends CborStructure<\n SessionTranscriptEncodedStructure,\n SessionTranscriptDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(sessionTranscriptEncodedSchema, sessionTranscriptDecodedSchema, {\n decode: ([deviceEngagementDataItem, eReaderKeyDataItem, handoverData]): SessionTranscriptDecodedStructure => {\n // TODO: this checks if it can be decoded, a smarter check could see that the handover\n // is e.g. OpenId4VP handover but a value in that handover is incorrect\n let handover: SessionTranscriptDecodedStructure['handover'] | null = null\n for (const HandoverStructure of supportedHandoverStructures) {\n handover = (HandoverStructure as typeof NfcHandover).tryDecodeHandover(handoverData)\n if (handover) break\n }\n\n if (!handover) {\n throw new Error('Could not establish handover structure for session transcript')\n }\n\n const deviceEngagement = deviceEngagementDataItem\n ? DeviceEngagement.fromEncodedStructure(deviceEngagementDataItem.data)\n : null\n const eReaderKey = eReaderKeyDataItem ? EReaderKey.fromEncodedStructure(eReaderKeyDataItem.data) : null\n\n return {\n deviceEngagement,\n eReaderKey,\n handover,\n }\n },\n encode: ({ deviceEngagement, eReaderKey, handover }): SessionTranscriptEncodedStructure => {\n if (handover.requiresDeviceEngagement && !deviceEngagement) {\n throw new Error(\n `Session transcript has no deviceEngagement but ${handover.constructor.name} handover requires deviceEngagement`\n )\n }\n\n if (!handover.requiresDeviceEngagement && deviceEngagement) {\n throw new Error(\n `Session transcript has deviceEngagement but ${handover.constructor.name} handover does not expect deviceEngagement.`\n )\n }\n\n if (handover.requiresReaderKey && !eReaderKey) {\n throw new Error(\n `Session transcript has no eReaderKey but ${handover.constructor.name} handover requires eReaderKey`\n )\n }\n\n if (!handover.requiresReaderKey && eReaderKey) {\n throw new Error(\n `Session transcript has eReaderKey but ${handover.constructor.name} handover does not expect eReaderKey.`\n )\n }\n\n return [\n deviceEngagement ? DataItem.fromData(deviceEngagement.encodedStructure) : null,\n eReaderKey ? DataItem.fromData(eReaderKey.encodedStructure) : null,\n handover.encodedStructure,\n ]\n },\n })\n }\n\n public get deviceEngagement() {\n return this.structure.deviceEngagement\n }\n\n public get eReaderKey() {\n return this.structure.eReaderKey\n }\n\n public get handover() {\n return this.structure.handover\n }\n\n public static create(options: SessionTranscriptOptions): SessionTranscript {\n return this.fromDecodedStructure({\n deviceEngagement: options.deviceEngagement ?? null,\n eReaderKey: options.eReaderKey ?? null,\n handover: options.handover,\n })\n }\n\n /**\n * Create a SessionTranscript for QR handover (ISO 18013-5 proximity presentation).\n *\n * For QR handover, exact CBOR bytes matter for session key derivation.\n * Use DeviceEngagement.decode() and EReaderKey.decode() to preserve original bytes -\n * calling encode() on decoded objects will return the identical bytes.\n */\n public static forQrHandover(options: { deviceEngagement: DeviceEngagement; eReaderKey: EReaderKey }) {\n return this.fromDecodedStructure({\n deviceEngagement: options.deviceEngagement,\n eReaderKey: options.eReaderKey,\n handover: QrHandover.create(),\n })\n }\n\n public static async forOid4VpDcApiDraft24(\n options: Oid4vpDcApiDraft24HandoverInfoOptions,\n ctx: Pick<MdocContext, 'crypto'>\n ) {\n const info = Oid4vpDcApiDraft24HandoverInfo.create(options)\n const handover = await Oid4vpDcApiHandover.create({ oid4vpDcApiHandoverInfo: info }, ctx)\n\n return this.fromDecodedStructure({ deviceEngagement: null, eReaderKey: null, handover })\n }\n\n public static async forOid4VpDcApi(options: Oid4vpDcApiHandoverInfoOptions, ctx: Pick<MdocContext, 'crypto'>) {\n const info = Oid4vpDcApiHandoverInfo.create(options)\n const handover = await Oid4vpDcApiHandover.create({ oid4vpDcApiHandoverInfo: info }, ctx)\n\n return this.fromDecodedStructure({ deviceEngagement: null, eReaderKey: null, handover })\n }\n\n public static async forOid4VpIae(options: Oid4vpIaeHandoverInfoOptions, ctx: Pick<MdocContext, 'crypto'>) {\n const info = Oid4vpIaeHandoverInfo.create(options)\n const handover = await Oid4vpIaeHandover.create({ oid4vpIaeHandoverInfo: info }, ctx)\n\n return this.fromDecodedStructure({ deviceEngagement: null, eReaderKey: null, handover })\n }\n\n public static async forOid4Vp(options: Oid4vpHandoverInfoOptions, ctx: Pick<MdocContext, 'crypto'>) {\n const info = Oid4vpHandoverInfo.create(options)\n const handover = await Oid4vpHandover.create({ oid4vpHandoverInfo: info }, ctx)\n\n return this.fromDecodedStructure({ deviceEngagement: null, eReaderKey: null, handover })\n }\n\n /**\n * Calculate the session transcript bytes as defined in 18013-7 first edition, based\n * on OpenID4VP draft 18.\n */\n public static async forOid4VpDraft18(\n options: { clientId: string; responseUri: string; verifierGeneratedNonce: string; mdocGeneratedNonce: string },\n ctx: Pick<MdocContext, 'crypto'>\n ) {\n const handover = await Oid4vpDraft18Handover.create(\n {\n clientId: options.clientId,\n nonce: options.verifierGeneratedNonce,\n mdocGeneratedNonce: options.mdocGeneratedNonce,\n responseUri: options.responseUri,\n },\n ctx\n )\n\n return this.fromDecodedStructure({ deviceEngagement: null, eReaderKey: null, handover })\n }\n}\n","import { z } from 'zod'\nimport {\n type AnyCborStructure,\n addExtension,\n CborStructure,\n type CborStructureStaticThis,\n cborDecode,\n cborEncode,\n type EncodedStructureType,\n} from '../cbor/index.js'\nimport type { MdocContext } from '../context.js'\nimport { SessionTranscript } from '../mdoc/models/session-transcript.js'\nimport { zUint8Array } from '../utils/zod.js'\nimport { CoseInvalidAlgorithmError, CosePayloadMustBeDefinedError } from './error.js'\nimport { Header, type MacAlgorithm } from './headers/defaults.js'\nimport {\n type ProtectedHeaderOptions,\n ProtectedHeaders,\n type ProtectedHeadersEncodedStructure,\n} from './headers/protected-headers.js'\nimport {\n type UnprotectedHeaderOptions,\n UnprotectedHeaders,\n type UnprotectedHeadersStructure,\n} from './headers/unprotected-headers.js'\nimport { coseKeyToJwk } from './key/jwk.js'\nimport type { CoseKey } from './key/key.js'\n\nconst mac0EncodedSchema = z.tuple([zUint8Array, z.map(z.unknown(), z.unknown()), zUint8Array.nullable(), zUint8Array])\n\nconst mac0DecodedSchema = z.object({\n protectedHeaders: z.instanceof(ProtectedHeaders),\n unprotectedHeaders: z.instanceof(UnprotectedHeaders),\n payload: zUint8Array.nullable(),\n tag: zUint8Array,\n})\n\nexport type Mac0EncodedStructure = z.infer<typeof mac0EncodedSchema>\nexport type Mac0DecodedStructure = z.infer<typeof mac0DecodedSchema>\n\nexport type Mac0Options = {\n protectedHeaders: ProtectedHeaders | ProtectedHeaderOptions['protectedHeaders']\n unprotectedHeaders: UnprotectedHeaders | UnprotectedHeaderOptions['unprotectedHeaders']\n externalAad?: Uint8Array\n\n payload?: Uint8Array | null\n detachedPayload?: Uint8Array\n\n privateKey: CoseKey\n ephemeralKey: CoseKey\n sessionTranscript: SessionTranscript | Uint8Array\n}\n\nexport class Mac0 extends CborStructure<Mac0EncodedStructure, Mac0DecodedStructure> {\n public static tag = 17\n\n public static override get encodingSchema() {\n return z.codec(mac0EncodedSchema, mac0DecodedSchema, {\n decode: ([protectedHeadersBytes, unprotectedHeadersMap, payload, tag]) => ({\n protectedHeaders: ProtectedHeaders.fromEncodedStructure(\n protectedHeadersBytes as ProtectedHeadersEncodedStructure\n ),\n unprotectedHeaders: UnprotectedHeaders.fromEncodedStructure(\n unprotectedHeadersMap as UnprotectedHeadersStructure\n ),\n payload,\n tag,\n }),\n encode: ({ protectedHeaders, unprotectedHeaders, payload, tag }) =>\n [\n protectedHeaders.encodedStructure,\n unprotectedHeaders.encodedStructure,\n payload,\n tag,\n ] satisfies Mac0EncodedStructure,\n })\n }\n\n public externalAad?: Uint8Array\n public detachedPayload?: Uint8Array\n\n public get protectedHeaders() {\n return this.structure.protectedHeaders\n }\n\n public get unprotectedHeaders() {\n return this.structure.unprotectedHeaders\n }\n\n public get payload() {\n return this.structure.payload\n }\n\n public get tag() {\n return this.structure.tag\n }\n\n public get toBeAuthenticated() {\n const payload = this.payload ?? this.detachedPayload\n\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n return Mac0.toBeAuthenticated({\n payload,\n protectedHeaders: this.protectedHeaders,\n externalAad: this.externalAad,\n })\n }\n\n /**\n * Decodes CBOR bytes into a Sign1 instance.\n * Uses the encodingSchema's decode() method to validate and transform the decoded data.\n */\n public static decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n const rawStructure = cborDecode(bytes)\n\n // May feel weird, but using new this makes TypeScript understand we may return a subclass\n return new this(\n // NOTE: If decoded with Mac0 tag, the cbor decoder already transforms to the class instances\n // In that case we create new instance based on the decoded structure, to ensure we create the\n // instance based on this (and ensure extended classes work)\n rawStructure instanceof Mac0\n ? rawStructure.decodedStructure\n : this.fromEncodedStructure(rawStructure as EncodedStructureType<T>).decodedStructure\n )\n }\n\n public static toBeAuthenticated(options: {\n payload: Uint8Array\n protectedHeaders: ProtectedHeaders\n externalAad?: Uint8Array\n }) {\n const toBeAuthenticated = ['MAC0', options.protectedHeaders.encodedStructure]\n if (options.externalAad) toBeAuthenticated.push(options.externalAad)\n toBeAuthenticated.push(options.payload)\n\n return cborEncode(toBeAuthenticated)\n }\n\n public get signatureAlgorithmName(): MacAlgorithm {\n const algorithm = (this.protectedHeaders.headers?.get(Header.Algorithm) ??\n this.unprotectedHeaders.headers?.get(Header.Algorithm)) as MacAlgorithm | undefined\n\n if (!algorithm) {\n throw new CoseInvalidAlgorithmError()\n }\n\n const algorithmName = coseKeyToJwk.algorithm(algorithm)\n\n if (!algorithmName) {\n throw new CoseInvalidAlgorithmError()\n }\n\n return algorithmName\n }\n\n public static async create(options: Mac0Options, ctx: Pick<MdocContext, 'crypto' | 'cose'>): Promise<Mac0> {\n const protectedHeaders =\n options.protectedHeaders instanceof ProtectedHeaders\n ? options.protectedHeaders\n : ProtectedHeaders.create({ protectedHeaders: options.protectedHeaders })\n\n const unprotectedHeaders =\n options.unprotectedHeaders instanceof UnprotectedHeaders\n ? options.unprotectedHeaders\n : UnprotectedHeaders.create({ unprotectedHeaders: options.unprotectedHeaders })\n\n const ephemeralMacKey = await ctx.crypto.calculateEphemeralMacKey({\n privateKey: options.privateKey.encode(),\n publicKey: options.ephemeralKey.encode(),\n sessionTranscriptBytes:\n options.sessionTranscript instanceof SessionTranscript\n ? options.sessionTranscript.encode({ asDataItem: true })\n : options.sessionTranscript,\n info: 'EMacKey',\n })\n\n const payload = options.payload ?? options.detachedPayload\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n const tag = await ctx.cose.mac0.sign({\n toBeAuthenticated: Mac0.toBeAuthenticated({\n payload,\n protectedHeaders: protectedHeaders,\n externalAad: options.externalAad,\n }),\n key: ephemeralMacKey,\n })\n\n const mac0 = this.fromDecodedStructure({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload ?? null,\n tag,\n })\n\n mac0.externalAad = options.externalAad\n mac0.detachedPayload = options.detachedPayload\n\n return mac0\n }\n}\n\naddExtension({\n Class: Mac0,\n tag: Mac0.tag,\n encode(instance: Mac0, encodeFn: (obj: unknown) => Uint8Array) {\n return encodeFn(instance.encodedStructure)\n },\n decode: (encoded) => Mac0.fromEncodedStructure(encoded as Mac0EncodedStructure),\n})\n","import z from 'zod'\nimport {\n type AnyCborStructure,\n addExtension,\n CborStructure,\n type CborStructureStaticThis,\n cborDecode,\n cborEncode,\n type EncodedStructureType,\n} from '../cbor/index.js'\nimport type { MdocContext } from '../context.js'\nimport { zUint8Array } from '../utils/zod.js'\nimport { CoseCertificateNotFoundError, CoseInvalidAlgorithmError, CosePayloadMustBeDefinedError } from './error.js'\nimport { Header, type SignatureAlgorithm } from './headers/defaults.js'\nimport {\n type ProtectedHeaderOptions,\n ProtectedHeaders,\n protectedHeadersEncodedStructure,\n} from './headers/protected-headers.js'\nimport {\n type UnprotectedHeaderOptions,\n UnprotectedHeaders,\n unprotectedHeadersStructure,\n} from './headers/unprotected-headers.js'\nimport { coseKeyToJwk } from './key/jwk.js'\nimport type { CoseKey } from './key/key.js'\n\nconst sign1EncodedSchema = z.tuple([\n // protected headers\n protectedHeadersEncodedStructure,\n // unprotected headers\n unprotectedHeadersStructure,\n // payload\n zUint8Array.nullable(),\n // signature\n zUint8Array,\n])\n\nconst sign1DecodedSchema = z.object({\n protected: z.instanceof(ProtectedHeaders),\n unprotected: z.instanceof(UnprotectedHeaders),\n payload: sign1EncodedSchema.def.items[2],\n signature: sign1EncodedSchema.def.items[3],\n})\n\nexport type Sign1EncodedStructure = z.infer<typeof sign1EncodedSchema>\nexport type Sign1DecodedStructure = z.infer<typeof sign1DecodedSchema>\n\nexport type Sign1Options = {\n protectedHeaders?: ProtectedHeaders | ProtectedHeaderOptions['protectedHeaders']\n unprotectedHeaders?: UnprotectedHeaders | UnprotectedHeaderOptions['unprotectedHeaders']\n signingKey: CoseKey\n\n payload?: Uint8Array | null\n detachedPayload?: Uint8Array\n\n externalAad?: Uint8Array\n}\n\nexport class Sign1 extends CborStructure<Sign1EncodedStructure, Sign1DecodedStructure> {\n public static tag = 18\n\n public static override get encodingSchema() {\n return z.codec(sign1EncodedSchema, sign1DecodedSchema, {\n encode: (decoded) =>\n [\n decoded.protected.encodedStructure,\n decoded.unprotected.encodedStructure,\n decoded.payload,\n decoded.signature,\n ] satisfies Sign1EncodedStructure,\n decode: ([protectedHeaders, unprotected, payload, signature]) => ({\n protected: ProtectedHeaders.fromEncodedStructure(protectedHeaders),\n unprotected: UnprotectedHeaders.fromEncodedStructure(unprotected),\n payload,\n signature,\n }),\n })\n }\n\n public detachedPayload?: Uint8Array\n public externalAad?: Uint8Array\n\n public get protectedHeaders() {\n return this.structure.protected\n }\n\n public get unprotectedHeaders() {\n return this.structure.unprotected\n }\n\n public get payload() {\n return this.structure.payload\n }\n\n public get signature() {\n return this.structure.signature\n }\n\n public get certificateChain() {\n return this.x5chain ?? []\n }\n\n public get certificate() {\n const [certificate] = this.certificateChain\n\n if (!certificate) {\n throw new CoseCertificateNotFoundError()\n }\n\n return certificate\n }\n\n public getIssuingCountry(ctx: Pick<MdocContext, 'x509'>) {\n const countryName = ctx.x509.getIssuerNameField({\n certificate: this.certificate,\n field: 'C',\n })[0]\n\n return countryName\n }\n\n public getIssuingStateOrProvince(ctx: Pick<MdocContext, 'x509'>) {\n const stateOrProvince = ctx.x509.getIssuerNameField({\n certificate: this.certificate,\n field: 'ST',\n })[0]\n\n return stateOrProvince\n }\n\n public get toBeSigned() {\n const payload = this.payload ?? this.detachedPayload\n\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n return Sign1.toBeSigned({\n payload,\n protectedHeaders: this.protectedHeaders,\n externalAad: this.externalAad,\n })\n }\n\n /**\n * Decodes CBOR bytes into a Sign1 instance.\n * Uses the encodingSchema's decode() method to validate and transform the decoded data.\n */\n public static decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n const rawStructure = cborDecode(bytes)\n\n // May feel weird, but using new this makes TypeScript understand we may return a subclass\n return new this(\n // NOTE: If decoded with Sign1 tag, the cbor decoder already transforms to the class instances\n // In that case we create new instance based on the decoded structure, to ensure we create the\n // instance based on this (and ensure extended classes work)\n rawStructure instanceof Sign1\n ? rawStructure.decodedStructure\n : this.fromEncodedStructure(rawStructure as EncodedStructureType<T>).decodedStructure\n )\n }\n\n public static toBeSigned(options: {\n payload: Uint8Array\n protectedHeaders: ProtectedHeaders\n externalAad?: Uint8Array\n }) {\n const toBeSigned = [\n 'Signature1',\n options.protectedHeaders.encodedStructure,\n options.externalAad ?? new Uint8Array(),\n options.payload,\n ]\n\n return cborEncode(toBeSigned)\n }\n\n public get signatureAlgorithmName(): string {\n // FIXME: why are we looking at the unprotected header for the alg?\n const algorithm = (this.protectedHeaders.headers?.get(Header.Algorithm) ??\n this.unprotectedHeaders.headers?.get(Header.Algorithm)) as SignatureAlgorithm | undefined\n\n if (!algorithm) {\n throw new CoseInvalidAlgorithmError()\n }\n\n const algorithmName = coseKeyToJwk.algorithm(algorithm)\n if (!algorithmName) {\n throw new CoseInvalidAlgorithmError()\n }\n\n return algorithmName\n }\n\n public get x5chain() {\n // TODO: typed keys for headers\n // FIXME: why are we looking at unprotected header for x5c?\n const x5chain =\n (this.protectedHeaders.headers?.get(Header.X5Chain) as Uint8Array | Uint8Array[] | undefined) ??\n (this.unprotectedHeaders.headers?.get(Header.X5Chain) as Uint8Array | Uint8Array[] | undefined)\n\n if (!x5chain?.[0]) {\n return undefined\n }\n\n return Array.isArray(x5chain) ? x5chain : [x5chain]\n }\n\n public async verifySignature(options: { key?: CoseKey }, ctx: Pick<MdocContext, 'cose' | 'x509'>) {\n const publicKey =\n options.key ??\n (await ctx.x509.getPublicKey({\n certificate: this.certificate,\n alg: this.signatureAlgorithmName,\n }))\n\n return await ctx.cose.sign1.verify({\n sign1: this,\n key: publicKey,\n })\n }\n\n public static async create(options: Sign1Options, ctx: Pick<MdocContext, 'cose'>) {\n const payload = options.payload ?? options.detachedPayload\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n const protectedHeaders =\n options.protectedHeaders instanceof ProtectedHeaders\n ? options.protectedHeaders\n : options.protectedHeaders\n ? ProtectedHeaders.fromDecodedStructure(options.protectedHeaders)\n : ProtectedHeaders.create({})\n\n const signature = await ctx.cose.sign1.sign({\n toBeSigned: Sign1.toBeSigned({\n payload,\n protectedHeaders,\n externalAad: options.externalAad,\n }),\n key: options.signingKey,\n })\n\n const sign1 = this.fromDecodedStructure({\n payload: options.payload ?? null,\n protected: protectedHeaders,\n unprotected:\n options.unprotectedHeaders instanceof UnprotectedHeaders\n ? options.unprotectedHeaders\n : options.unprotectedHeaders\n ? UnprotectedHeaders.fromEncodedStructure(options.unprotectedHeaders)\n : UnprotectedHeaders.create({}),\n signature,\n })\n\n sign1.detachedPayload = options.detachedPayload\n sign1.externalAad = options.externalAad\n\n return sign1\n }\n}\n\naddExtension({\n Class: Sign1,\n tag: Sign1.tag,\n encode(instance: Sign1, encodeFn: (obj: unknown) => Uint8Array) {\n return encodeFn(instance)\n },\n decode: (encoded) => Sign1.fromEncodedStructure(encoded as Sign1EncodedStructure),\n})\n","// biome-ignore format: no explanation\nexport class MdlError extends Error {\n constructor(message: string = new.target.name) {\n super(message)\n }\n}\n\nexport class MdlParseError extends MdlError {}\nexport class PresentationDefinitionOrDocRequestsAreRequiredError extends MdlError {}\nexport class SessionTranscriptOrSessionTranscriptBytesAreRequiredError extends MdlError {}\nexport class DuplicateNamespaceInIssuerNamespacesError extends MdlError {}\nexport class DuplicateDocumentInDeviceResponseError extends MdlError {}\nexport class EitherSignatureOrMacMustBeProvidedError extends MdlError {}\n","import { MdlError } from './errors.js'\n\nexport interface VerificationAssessment {\n status: 'PASSED' | 'FAILED' | 'WARNING'\n category: 'DOCUMENT_FORMAT' | 'DEVICE_AUTH' | 'ISSUER_AUTH' | 'DATA_INTEGRITY' | 'READER_AUTH'\n check: string\n reason?: string\n}\n\nexport type VerificationCallback = (item: VerificationAssessment) => void\n\nexport const defaultVerificationCallback: VerificationCallback = (verification) => {\n if (verification.status !== 'FAILED') return\n throw new MdlError(verification.reason ?? verification.check)\n}\n\nexport const onCategoryCheck = (onCheck: VerificationCallback, category: VerificationAssessment['category']) => {\n return (item: Omit<VerificationAssessment, 'category'>) => {\n onCheck({ ...item, category })\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport type { DataElementValue } from './data-element-value'\n\n// Zod schema for DeviceSignedItems\nexport const deviceSignedItemsSchema = z.map(z.string(), z.unknown())\n\nexport type DeviceSignedItemsStructure = z.infer<typeof deviceSignedItemsSchema>\n\nexport type DeviceSignedItemsOptions = {\n deviceSignedItems: Map<DataElementIdentifier, DataElementValue>\n}\n\nexport class DeviceSignedItems extends CborStructure<DeviceSignedItemsStructure> {\n public static override get encodingSchema() {\n return deviceSignedItemsSchema\n }\n\n public get deviceSignedItems() {\n return this.structure\n }\n\n public static create(options: DeviceSignedItemsOptions): DeviceSignedItems {\n return this.fromEncodedStructure(options.deviceSignedItems)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { DeviceSignedItems, type DeviceSignedItemsStructure, deviceSignedItemsSchema } from './device-signed-items'\nimport type { Namespace } from './namespace'\n\nconst deviceNamespacesEncodedSchema = z.map(z.string(), deviceSignedItemsSchema)\nconst deviceNamespacesDecodedSchema = z.map(z.string(), z.instanceof(DeviceSignedItems))\n\nexport type DeviceNamespacesDecodedStructure = z.infer<typeof deviceNamespacesDecodedSchema>\nexport type DeviceNamespacesEncodedStructure = z.infer<typeof deviceNamespacesEncodedSchema>\n\nexport type DeviceNamespacesOptions = {\n deviceNamespaces: Map<Namespace, DeviceSignedItems>\n}\n\nexport class DeviceNamespaces extends CborStructure<\n DeviceNamespacesEncodedStructure,\n DeviceNamespacesDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(deviceNamespacesEncodedSchema, deviceNamespacesDecodedSchema, {\n decode: (input) => {\n const deviceNamespaces = new Map<Namespace, DeviceSignedItems>()\n input.forEach((value, key) => {\n deviceNamespaces.set(key, DeviceSignedItems.fromEncodedStructure(value as DeviceSignedItemsStructure))\n })\n return deviceNamespaces\n },\n encode: (output) => {\n const map = new Map()\n output.forEach((value, key) => {\n map.set(key, value.encodedStructure)\n })\n return map\n },\n })\n }\n\n public get deviceNamespaces() {\n return this.structure\n }\n\n public static create(options: DeviceNamespacesOptions): DeviceNamespaces {\n return this.fromDecodedStructure(options.deviceNamespaces)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure, DataItem } from '../../cbor'\nimport { DeviceNamespaces, type DeviceNamespacesEncodedStructure } from './device-namespaces'\nimport type { DocType } from './doctype'\nimport { SessionTranscript, sessionTranscriptEncodedSchema } from './session-transcript'\n\nconst deviceAuthenticationEncodedSchema = z.tuple([\n z.literal('DeviceAuthentication'),\n sessionTranscriptEncodedSchema,\n z.string(),\n z.instanceof<typeof DataItem<DeviceNamespacesEncodedStructure>>(DataItem),\n])\n\nconst deviceAuthenticationDecodedSchema = z.object({\n sessionTranscript: z.instanceof(SessionTranscript),\n docType: z.string(),\n deviceNamespaces: z.instanceof(DeviceNamespaces),\n})\n\nexport type DeviceAuthenticationDecodedStructure = z.infer<typeof deviceAuthenticationDecodedSchema>\nexport type DeviceAuthenticationEncodedStructure = z.infer<typeof deviceAuthenticationEncodedSchema>\n\nexport type DeviceAuthenticationOptions = {\n sessionTranscript: SessionTranscript | Uint8Array\n docType: DocType\n deviceNamespaces: DeviceNamespaces\n}\n\nexport class DeviceAuthentication extends CborStructure<\n DeviceAuthenticationEncodedStructure,\n DeviceAuthenticationDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(deviceAuthenticationEncodedSchema, deviceAuthenticationDecodedSchema, {\n decode: ([, sessionTranscript, docType, deviceNamespacesDataItem]) => ({\n sessionTranscript: SessionTranscript.fromEncodedStructure(sessionTranscript),\n docType,\n deviceNamespaces: DeviceNamespaces.fromEncodedStructure(deviceNamespacesDataItem.data),\n }),\n encode: ({ sessionTranscript, docType, deviceNamespaces }) =>\n [\n 'DeviceAuthentication',\n sessionTranscript.encodedStructure,\n docType,\n DataItem.fromData(deviceNamespaces.encodedStructure),\n ] satisfies DeviceAuthenticationEncodedStructure,\n })\n }\n\n public get sessionTranscript() {\n return this.structure.sessionTranscript\n }\n\n public get docType() {\n return this.structure.docType\n }\n\n public get deviceNamespaces() {\n return this.structure.deviceNamespaces\n }\n\n public static create(options: DeviceAuthenticationOptions): DeviceAuthentication {\n const sessionTranscript =\n options.sessionTranscript instanceof SessionTranscript\n ? options.sessionTranscript\n : SessionTranscript.decode(options.sessionTranscript)\n\n return this.fromDecodedStructure({\n sessionTranscript,\n docType: options.docType,\n deviceNamespaces: options.deviceNamespaces,\n })\n }\n}\n","import type { MdocContext } from '../../context'\nimport type { CoseKey, Mac0Options } from '../../cose'\nimport { Mac0, type Mac0DecodedStructure, type Mac0EncodedStructure } from '../../cose/mac0'\nimport { SessionTranscript } from './session-transcript'\n\nexport type DeviceMacEncodedStructure = Mac0EncodedStructure\nexport type DeviceMacDecodedStructure = Mac0DecodedStructure\nexport type DeviceMacOptions = Mac0Options\n\nexport class DeviceMac extends Mac0 {\n public async verify(\n options: {\n publicKey: CoseKey\n privateKey: CoseKey\n info?: 'EMacKey' | 'SKReader' | 'SKDevice'\n sessionTranscript: SessionTranscript | Uint8Array\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose'>\n ) {\n const key = await ctx.crypto.calculateEphemeralMacKey({\n privateKey: options.privateKey.privateKey,\n publicKey: options.publicKey.publicKey,\n sessionTranscriptBytes:\n options.sessionTranscript instanceof SessionTranscript\n ? options.sessionTranscript.encode({ asDataItem: true })\n : options.sessionTranscript,\n info: options.info ?? 'EMacKey',\n })\n\n return ctx.cose.mac0.verify({\n mac0: this,\n key,\n })\n }\n\n public static async create(options: DeviceMacOptions, ctx: Pick<MdocContext, 'cose' | 'crypto'>) {\n return super.create(options, ctx) as Promise<DeviceMac>\n }\n}\n","import type { MdocContext } from '../../context'\nimport { Sign1, type Sign1DecodedStructure, type Sign1EncodedStructure, type Sign1Options } from '../../cose/sign1'\n\nexport type DeviceSignatureEncodedStructure = Sign1EncodedStructure\nexport type DeviceSignatureDecodedStructure = Sign1DecodedStructure\nexport type DeviceSignatureOptions = Sign1Options\n\nexport class DeviceSignature extends Sign1 {\n // TODO: super should be generic, so we don't need this\n public static create(options: DeviceSignatureOptions, ctx: Pick<MdocContext, 'cose'>) {\n return super.create(options, ctx) as Promise<DeviceSignature>\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport type { MdocContext } from '../../context'\nimport { type CoseKey, MacAlgorithm } from '../../cose'\nimport { TypedMap, typedMap } from '../../utils'\nimport { defaultVerificationCallback, onCategoryCheck, type VerificationCallback } from '../check-callback'\nimport { DeviceAuthentication } from './device-authentication'\nimport { DeviceMac, type DeviceMacEncodedStructure } from './device-mac'\nimport { DeviceSignature, type DeviceSignatureEncodedStructure } from './device-signature'\nimport type { Document } from './document'\nimport type { SessionTranscript } from './session-transcript'\n\nconst deviceAuthSchema = typedMap([\n ['deviceSignature', z.instanceof(DeviceSignature).exactOptional()],\n ['deviceMac', z.instanceof(DeviceMac).exactOptional()],\n] as const).refine(\n (map) => [map.get('deviceMac'), map.get('deviceSignature')].filter((i) => i !== undefined).length === 1,\n { error: () => 'deviceAuth must contain either a deviceMac or deviceSignature, but not both or neither' }\n)\n\nexport type DeviceAuthDecodedStructure = z.output<typeof deviceAuthSchema>\nexport type DeviceAuthEncodedStructure = z.input<typeof deviceAuthSchema>\n\nexport type DeviceAuthOptions = {\n deviceSignature?: DeviceSignature\n deviceMac?: DeviceMac\n}\n\nexport class DeviceAuth extends CborStructure<DeviceAuthEncodedStructure, DeviceAuthDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(deviceAuthSchema.in, deviceAuthSchema.out, {\n decode: (input) => {\n const map: DeviceAuthDecodedStructure = TypedMap.fromMap(input)\n\n if (input.has('deviceSignature')) {\n map.set(\n 'deviceSignature',\n DeviceSignature.fromEncodedStructure(input.get('deviceSignature') as DeviceSignatureEncodedStructure)\n )\n }\n if (input.has('deviceMac')) {\n map.set('deviceMac', DeviceMac.fromEncodedStructure(input.get('deviceMac') as DeviceMacEncodedStructure))\n }\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n const deviceSignature = output.get('deviceSignature')\n if (deviceSignature) {\n map.set('deviceSignature', deviceSignature.encodedStructure)\n }\n const deviceMac = output.get('deviceMac')\n if (deviceMac) {\n map.set('deviceMac', deviceMac.encodedStructure)\n }\n return map\n },\n })\n }\n\n public get deviceSignature() {\n return this.structure.get('deviceSignature')\n }\n\n public get deviceMac() {\n return this.structure.get('deviceMac')\n }\n\n public async verify(\n options: {\n document: Document\n verificationCallback?: VerificationCallback\n ephemeralMacPrivateKey?: CoseKey\n sessionTranscript: SessionTranscript | Uint8Array\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose'>\n ) {\n const verificationCallback = options.verificationCallback ?? defaultVerificationCallback\n\n const onCheck = onCategoryCheck(verificationCallback, 'DEVICE_AUTH')\n\n const { deviceKey } = options.document.issuerSigned.issuerAuth.mobileSecurityObject.deviceKeyInfo\n\n const deviceMac = this.structure.get('deviceMac')\n const deviceSignature = this.structure.get('deviceSignature')\n\n if (!deviceMac && !deviceSignature) {\n onCheck({\n status: 'FAILED',\n check: 'Device Auth must contain a deviceSignature or deviceMac element',\n })\n return\n }\n\n const deviceAuthenticationBytes = DeviceAuthentication.create({\n sessionTranscript: options.sessionTranscript,\n docType: options.document.docType,\n deviceNamespaces: options.document.deviceSigned.deviceNamespaces,\n }).encode({ asDataItem: true })\n\n if (deviceSignature) {\n try {\n deviceSignature.detachedPayload = deviceAuthenticationBytes\n const verificationResult = await ctx.cose.sign1.verify({ sign1: deviceSignature, key: deviceKey })\n\n onCheck({\n status: verificationResult ? 'PASSED' : 'FAILED',\n check: 'Device signature must be valid',\n })\n } catch (err) {\n onCheck({\n status: 'FAILED',\n check: 'Device signature must be valid',\n reason: `Unable to verify deviceAuth signature (ECDSA/EdDSA): ${err instanceof Error ? err.message : 'Unknown error'}`,\n })\n }\n return\n }\n\n if (deviceMac) {\n if (deviceMac.signatureAlgorithmName !== MacAlgorithm.HS256) {\n onCheck({\n status: 'FAILED',\n check: 'Device MAC must use alg 5 (HMAC 256/256)',\n })\n return\n }\n\n onCheck({\n status: options.ephemeralMacPrivateKey ? 'PASSED' : 'FAILED',\n check: 'Ephemeral private key must be present when using MAC authentication',\n })\n\n if (!options.ephemeralMacPrivateKey) {\n return\n }\n\n try {\n deviceMac.detachedPayload = deviceAuthenticationBytes\n const isValid = await deviceMac.verify(\n {\n publicKey: deviceKey,\n privateKey: options.ephemeralMacPrivateKey,\n sessionTranscript: options.sessionTranscript,\n info: 'EMacKey',\n },\n ctx\n )\n\n onCheck({\n status: isValid ? 'PASSED' : 'FAILED',\n check: 'Device MAC must be valid',\n })\n } catch (err) {\n onCheck({\n status: 'FAILED',\n check: 'Device MAC must be valid',\n reason: `Unable to verify deviceAuth MAC: ${err instanceof Error ? err.message : 'Unknown error'}`,\n })\n }\n }\n\n onCheck({\n status: 'FAILED',\n check: 'No Device Signature or Device Mac found on Device Auth',\n reason: 'No Device Signature or Device Mac found on Device Auth',\n })\n }\n\n public static create(options: DeviceAuthOptions): DeviceAuth {\n const map: DeviceAuthDecodedStructure = new TypedMap([])\n if (options.deviceSignature) {\n map.set('deviceSignature', options.deviceSignature)\n }\n if (options.deviceMac) {\n map.set('deviceMac', options.deviceMac)\n }\n\n return this.fromDecodedStructure(map)\n }\n}\n","import {\n CoseKey,\n type CoseKeyDecodedStructure,\n type CoseKeyEncodedStructure,\n type CoseKeyOptions,\n} from '../../cose/key/key'\n\nexport type DeviceKeyDecodedStructure = CoseKeyDecodedStructure\nexport type DeviceKeyEncodedStructure = CoseKeyEncodedStructure\nexport type DeviceKeyOptions = CoseKeyOptions\n\n// DeviceKey is just a CoseKey with a different name/type for clarity in mdoc context\nexport class DeviceKey extends CoseKey {}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { TypedMap, typedMap } from '../../utils'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport type { Namespace } from './namespace'\n\nconst keyAuthorizationsSchema = typedMap([\n ['nameSpaces', z.array(z.string()).exactOptional()],\n ['dataElements', z.map(z.string(), z.array(z.string())).exactOptional()],\n] as const)\n\nexport type KeyAuthorizationsEncodedStructure = z.input<typeof keyAuthorizationsSchema>\nexport type KeyAuthorizationsDecodedStructure = z.output<typeof keyAuthorizationsSchema>\n\nexport type KeyAuthorizationsOptions = {\n namespaces?: Array<Namespace>\n dataElements?: Map<Namespace, Array<DataElementIdentifier>>\n}\n\nexport class KeyAuthorizations extends CborStructure<\n KeyAuthorizationsEncodedStructure,\n KeyAuthorizationsDecodedStructure\n> {\n public static override get encodingSchema() {\n return keyAuthorizationsSchema\n }\n\n public get namespaces() {\n return this.structure.get('nameSpaces')\n }\n\n public get dataElements() {\n return this.structure.get('dataElements')\n }\n\n public static create(options: KeyAuthorizationsOptions): KeyAuthorizations {\n const map: KeyAuthorizationsDecodedStructure = new TypedMap([])\n\n if (options.namespaces !== undefined) {\n map.set('nameSpaces', options.namespaces)\n }\n\n if (options.dataElements !== undefined) {\n map.set('dataElements', options.dataElements)\n }\n\n return this.fromDecodedStructure(map)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\n\n// KeyInfo uses integer keys (Map<number, unknown>)\n// Per spec: KeyInfo = { * int => any }\nconst keyInfoSchema = z.map(z.number(), z.unknown())\n\nexport type KeyInfoEncodedStructure = z.input<typeof keyInfoSchema>\nexport type KeyInfoDecodedStructure = z.output<typeof keyInfoSchema>\n\nexport type KeyInfoOptions = {\n keyInfo: Map<number, unknown>\n}\n\nexport class KeyInfo extends CborStructure<KeyInfoEncodedStructure, KeyInfoDecodedStructure> {\n public static override get encodingSchema() {\n return keyInfoSchema\n }\n\n public get keyInfo() {\n return this.structure\n }\n\n public static create(options: KeyInfoOptions): KeyInfo {\n return this.fromEncodedStructure(options.keyInfo)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { TypedMap, typedMap } from '../../utils'\nimport { DeviceKey, type DeviceKeyEncodedStructure } from './device-key'\nimport { KeyAuthorizations, type KeyAuthorizationsEncodedStructure } from './key-authorizations'\nimport { KeyInfo, type KeyInfoEncodedStructure } from './key-info'\n\nconst deviceKeyInfoSchema = typedMap([\n ['deviceKey', z.instanceof(DeviceKey)],\n ['keyAuthorizations', z.instanceof(KeyAuthorizations).exactOptional()],\n ['keyInfo', z.instanceof(KeyInfo).exactOptional()],\n] as const)\n\nexport type DeviceKeyInfoDecodedStructure = z.output<typeof deviceKeyInfoSchema>\nexport type DeviceKeyInfoEncodedStructure = z.input<typeof deviceKeyInfoSchema>\n\nexport type DeviceKeyInfoOptions = {\n deviceKey: DeviceKey\n keyAuthorizations?: KeyAuthorizations\n keyInfo?: KeyInfo\n}\n\nexport class DeviceKeyInfo extends CborStructure<DeviceKeyInfoEncodedStructure, DeviceKeyInfoDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(deviceKeyInfoSchema.in, deviceKeyInfoSchema.out, {\n decode: (input) => {\n const map: DeviceKeyInfoDecodedStructure = TypedMap.fromMap(input)\n\n map.set('deviceKey', DeviceKey.fromEncodedStructure(input.get('deviceKey') as DeviceKeyEncodedStructure))\n\n if (input.has('keyAuthorizations')) {\n map.set(\n 'keyAuthorizations',\n KeyAuthorizations.fromEncodedStructure(input.get('keyAuthorizations') as KeyAuthorizationsEncodedStructure)\n )\n }\n if (input.has('keyInfo')) {\n map.set('keyInfo', KeyInfo.fromEncodedStructure(input.get('keyInfo') as KeyInfoEncodedStructure))\n }\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n map.set('deviceKey', output.get('deviceKey').encodedStructure)\n\n const keyAuthorizations = output.get('keyAuthorizations')\n if (keyAuthorizations) {\n map.set('keyAuthorizations', keyAuthorizations.encodedStructure)\n }\n const keyInfo = output.get('keyInfo')\n if (keyInfo) {\n map.set('keyInfo', keyInfo.encodedStructure)\n }\n return map\n },\n })\n }\n\n public get deviceKey() {\n return this.structure.get('deviceKey')\n }\n\n public get keyAuthorizations() {\n return this.structure.get('keyAuthorizations')\n }\n\n public get keyInfo() {\n return this.structure.get('keyInfo')\n }\n\n public static create(options: DeviceKeyInfoOptions): DeviceKeyInfo {\n const map: DeviceKeyInfoDecodedStructure = new TypedMap([['deviceKey', options.deviceKey]])\n if (options.keyAuthorizations) {\n map.set('keyAuthorizations', options.keyAuthorizations)\n }\n if (options.keyInfo) {\n map.set('keyInfo', options.keyInfo)\n }\n return this.fromDecodedStructure(map)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { typedMap } from '../../utils'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport type { DocType } from './doctype'\nimport type { IntentToRetain } from './intent-to-retain'\nimport type { Namespace } from './namespace'\n\nconst namespacesSchema = z.map(z.string(), z.map(z.string(), z.boolean()))\n\n// Zod schema for ItemsRequest\nconst itemsRequestSchema = typedMap([\n ['docType', z.string()],\n ['nameSpaces', namespacesSchema],\n] as const)\n\nexport type ItemsRequestEncodedStructure = z.input<typeof itemsRequestSchema>\nexport type ItemsRequestDecodedStructure = z.output<typeof itemsRequestSchema>\n\ntype NamespacesStructure = z.infer<typeof namespacesSchema>\n\nexport type ItemsRequestOptions = {\n docType: DocType\n namespaces:\n | NamespacesStructure\n // We allow record when creating for easier usage\n | Record<Namespace, Record<DataElementIdentifier, IntentToRetain>>\n}\n\nexport class ItemsRequest extends CborStructure<ItemsRequestEncodedStructure, ItemsRequestDecodedStructure> {\n public static override get encodingSchema() {\n return itemsRequestSchema\n }\n\n public get docType() {\n return this.structure.get('docType')\n }\n\n public get namespaces() {\n return this.structure.get('nameSpaces')\n }\n\n public static create(options: ItemsRequestOptions): ItemsRequest {\n const namespaces =\n options.namespaces instanceof Map\n ? options.namespaces\n : new Map(Object.entries(options.namespaces).map(([ns, inner]) => [ns, new Map(Object.entries(inner))]))\n\n const structure = new Map<unknown, unknown>([\n ['docType', options.docType],\n ['nameSpaces', namespaces],\n ])\n\n return this.fromEncodedStructure(structure)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure, DataItem } from '../../cbor'\nimport { ItemsRequest, type ItemsRequestEncodedStructure } from './items-request'\nimport { SessionTranscript, sessionTranscriptEncodedSchema } from './session-transcript'\n\nconst readerAuthenticationEncodedSchema = z.tuple([\n z.literal('ReaderAuthentication'),\n sessionTranscriptEncodedSchema,\n z.instanceof<typeof DataItem<ItemsRequestEncodedStructure>>(DataItem),\n])\n\nconst readerAuthenticationDecodedSchema = z.object({\n sessionTranscript: z.instanceof(SessionTranscript),\n itemsRequest: z.instanceof(ItemsRequest),\n})\n\nexport type ReaderAuthenticationDecodedStructure = z.infer<typeof readerAuthenticationDecodedSchema>\nexport type ReaderAuthenticationEncodedStructure = z.infer<typeof readerAuthenticationEncodedSchema>\n\nexport type ReaderAuthenticationOptions = {\n sessionTranscript: SessionTranscript\n itemsRequest: ItemsRequest\n}\n\nexport class ReaderAuthentication extends CborStructure<\n ReaderAuthenticationEncodedStructure,\n ReaderAuthenticationDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(readerAuthenticationEncodedSchema, readerAuthenticationDecodedSchema, {\n decode: ([, sessionTranscript, itemsRequestDataItem]) => ({\n sessionTranscript: SessionTranscript.fromEncodedStructure(sessionTranscript),\n itemsRequest: ItemsRequest.fromEncodedStructure(itemsRequestDataItem.data),\n }),\n encode: ({ sessionTranscript, itemsRequest }) =>\n [\n 'ReaderAuthentication',\n sessionTranscript.encodedStructure,\n DataItem.fromData(itemsRequest.encodedStructure),\n ] satisfies ReaderAuthenticationEncodedStructure,\n })\n }\n\n public get sessionTranscript() {\n return this.structure.sessionTranscript\n }\n\n public get itemsRequest() {\n return this.structure.itemsRequest\n }\n\n public static create(options: ReaderAuthenticationOptions): ReaderAuthentication {\n return this.fromDecodedStructure({\n sessionTranscript: options.sessionTranscript,\n itemsRequest: options.itemsRequest,\n })\n }\n}\n","import type { MdocContext } from '../../context'\nimport { Sign1, type Sign1DecodedStructure, type Sign1EncodedStructure, type Sign1Options } from '../../cose/sign1'\nimport { defaultVerificationCallback, onCategoryCheck, type VerificationCallback } from '../check-callback'\nimport { ReaderAuthentication, type ReaderAuthenticationOptions } from './reader-authentication'\n\nexport type ReaderAuthEncodedStructure = Sign1EncodedStructure\nexport type ReaderAuthDecodedStructure = Sign1DecodedStructure\nexport type ReaderAuthOptions = Sign1Options\n\nexport class ReaderAuth extends Sign1 {\n public async verify(\n options: {\n readerAuthentication: ReaderAuthentication | ReaderAuthenticationOptions\n verificationCallback?: VerificationCallback\n },\n ctx: Pick<MdocContext, 'cose' | 'x509'>\n ) {\n const readerAuthentication =\n options.readerAuthentication instanceof ReaderAuthentication\n ? options.readerAuthentication\n : new ReaderAuthentication(options.readerAuthentication)\n\n const verificationCallback = options.verificationCallback ?? defaultVerificationCallback\n\n const onCheck = onCategoryCheck(verificationCallback, 'READER_AUTH')\n\n this.detachedPayload = readerAuthentication.encode({ asDataItem: true })\n\n const isValid = await this.verifySignature({}, ctx)\n\n onCheck({\n status: isValid ? 'PASSED' : 'FAILED',\n check: 'Signature is invalid on the reader auth',\n reason: 'Signature is invalid on the reader auth',\n })\n }\n\n // TODO: super should be generic, so we don't need this\n public static create(options: ReaderAuthOptions, ctx: Pick<MdocContext, 'cose'>) {\n return super.create(options, ctx) as Promise<ReaderAuth>\n }\n}\n","import { z } from 'zod'\nimport { CborStructure, DataItem } from '../../cbor'\nimport { TypedMap, typedMap } from '../../utils'\nimport { ItemsRequest, type ItemsRequestEncodedStructure } from './items-request'\nimport { ReaderAuth, type ReaderAuthEncodedStructure } from './reader-auth'\n\nconst docRequestSchema = typedMap([\n ['itemsRequest', z.instanceof(ItemsRequest)],\n ['readerAuth', z.instanceof(ReaderAuth).exactOptional()],\n] as const)\n\nexport type DocRequestDecodedStructure = z.output<typeof docRequestSchema>\nexport type DocRequestEncodedStructure = z.input<typeof docRequestSchema>\n\nexport type DocRequestOptions = {\n itemsRequest: ItemsRequest\n readerAuth?: ReaderAuth\n}\n\nexport class DocRequest extends CborStructure<DocRequestEncodedStructure, DocRequestDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(docRequestSchema.in, docRequestSchema.out, {\n decode: (input) => {\n const map: DocRequestDecodedStructure = TypedMap.fromMap(input)\n\n const itemsRequestData = input.get('itemsRequest') as DataItem\n map.set(\n 'itemsRequest',\n ItemsRequest.fromEncodedStructure(itemsRequestData.data as ItemsRequestEncodedStructure)\n )\n\n if (input.has('readerAuth')) {\n map.set('readerAuth', ReaderAuth.fromEncodedStructure(input.get('readerAuth') as ReaderAuthEncodedStructure))\n }\n\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n map.set('itemsRequest', DataItem.fromData(output.get('itemsRequest').encodedStructure))\n\n const readerAuth = output.get('readerAuth')\n if (readerAuth) {\n map.set('readerAuth', readerAuth.encodedStructure)\n }\n\n return map\n },\n })\n }\n\n public get itemsRequest() {\n return this.structure.get('itemsRequest')\n }\n\n public get readerAuth() {\n return this.structure.get('readerAuth')\n }\n\n public static create(options: DocRequestOptions): DocRequest {\n const map: DocRequestDecodedStructure = new TypedMap([['itemsRequest', options.itemsRequest]])\n if (options.readerAuth) {\n map.set('readerAuth', options.readerAuth)\n }\n return this.fromDecodedStructure(map)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { TypedMap, typedMap } from '../../utils'\nimport { DocRequest, type DocRequestEncodedStructure } from './doc-request'\n\nconst deviceRequestSchema = typedMap([\n ['version', z.string()],\n ['docRequests', z.array(z.instanceof(DocRequest))],\n] as const)\n\nexport type DeviceRequestDecodedStructure = z.output<typeof deviceRequestSchema>\nexport type DeviceRequestEncodedStructure = z.input<typeof deviceRequestSchema>\n\nexport type DeviceRequestOptions = {\n version?: string\n docRequests: Array<DocRequest>\n}\n\nexport class DeviceRequest extends CborStructure<DeviceRequestEncodedStructure, DeviceRequestDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(deviceRequestSchema.in, deviceRequestSchema.out, {\n decode: (input) => {\n const map: DeviceRequestDecodedStructure = TypedMap.fromMap(input)\n const docRequests = input.get('docRequests') as unknown[]\n\n map.set(\n 'docRequests',\n docRequests.map((dr) => DocRequest.fromEncodedStructure(dr as DocRequestEncodedStructure))\n )\n\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n map.set(\n 'docRequests',\n output.get('docRequests').map((dr) => dr.encodedStructure)\n )\n\n return map\n },\n })\n }\n\n public get version() {\n return this.structure.get('version')\n }\n\n public get docRequests() {\n return this.structure.get('docRequests')\n }\n\n public static create(options: DeviceRequestOptions): DeviceRequest {\n const map: DeviceRequestDecodedStructure = new TypedMap([\n ['version', options.version ?? '1.0'],\n ['docRequests', options.docRequests],\n ])\n return this.fromDecodedStructure(map)\n }\n}\n","import type { DocType } from '../mdoc/models/doctype'\nimport type { IssuerSigned } from '../mdoc/models/issuer-signed'\n\nexport const findIssuerSigned = (is: Array<IssuerSigned>, docType: DocType) => {\n const issuerSigned = is.filter((i) => i.issuerAuth.mobileSecurityObject.docType === docType)\n\n if (!issuerSigned || !issuerSigned[0]) {\n throw new Error(`No Issuer Signed matching docType '${docType}'`)\n }\n\n if (issuerSigned.length > 1) {\n throw new Error(`Multiple Issuer Signed matching docType '${docType}'`)\n }\n\n return issuerSigned[0]\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport type { MdocContext } from '../../context'\nimport { compareBytes, typedMap } from '../../utils'\nimport { zUint8Array } from '../../utils/zod'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport type { DataElementValue } from './data-element-value'\nimport type { IssuerAuth } from './issuer-auth'\nimport type { Namespace } from './namespace'\n\n// IssuerSignedItem uses string keys per spec:\n// IssuerSignedItem = {\n// \"digestID\" : uint,\n// \"random\" : bstr,\n// \"elementIdentifier\" : DataElementIdentifier,\n// \"elementValue\" : DataElementValue\n// }\nexport const issuerSignedItemSchema = typedMap([\n ['digestID', z.number()],\n ['random', zUint8Array],\n ['elementIdentifier', z.string()],\n ['elementValue', z.unknown()],\n])\n\nexport type IssuerSignedItemEncodedStructure = z.input<typeof issuerSignedItemSchema>\nexport type IssuerSignedItemDecodedStructure = z.output<typeof issuerSignedItemSchema>\n\n// NOTE: Id vs ID above (user-facing API uses digestId, CBOR uses digestID)\nexport type IssuerSignedItemOptions = {\n digestId: number\n random: Uint8Array\n elementIdentifier: DataElementIdentifier\n elementValue: DataElementValue\n}\n\nexport class IssuerSignedItem extends CborStructure<\n IssuerSignedItemEncodedStructure,\n IssuerSignedItemDecodedStructure\n> {\n public static override get encodingSchema() {\n return issuerSignedItemSchema\n }\n\n public get random() {\n return this.structure.get('random')\n }\n\n public get elementIdentifier() {\n return this.structure.get('elementIdentifier')\n }\n\n public get elementValue() {\n return this.structure.get('elementValue')\n }\n\n public get digestId() {\n return this.structure.get('digestID')\n }\n\n public async isValid(namespace: Namespace, issuerAuth: IssuerAuth, ctx: Pick<MdocContext, 'crypto'>) {\n const digest = await ctx.crypto.digest({\n digestAlgorithm: issuerAuth.mobileSecurityObject.digestAlgorithm,\n bytes: this.encode({ asDataItem: true }),\n })\n\n const valueDigests = issuerAuth.mobileSecurityObject.valueDigests.valueDigests\n const digests = valueDigests.get(namespace)\n\n if (!digests) {\n return false\n }\n\n const expectedDigest = digests.get(this.digestId)\n\n return expectedDigest !== undefined && compareBytes(digest, expectedDigest)\n }\n\n public matchCertificate(issuerAuth: IssuerAuth, ctx: Pick<MdocContext, 'x509'>) {\n if (this.elementIdentifier === 'issuing_country') {\n return this.elementValue === issuerAuth.getIssuingCountry(ctx)\n }\n\n if (this.elementIdentifier === 'issuing_jurisdiction') {\n return this.elementValue === issuerAuth.getIssuingStateOrProvince(ctx)\n }\n\n return false\n }\n\n public static fromOptions(options: IssuerSignedItemOptions) {\n const map = new Map([\n ['digestID', options.digestId],\n ['random', options.random],\n ['elementIdentifier', options.elementIdentifier],\n ['elementValue', options.elementValue],\n ])\n return this.fromEncodedStructure(map)\n }\n}\n","import z from 'zod'\nimport { CborStructure, DataItem } from '../../cbor'\nimport { IssuerSignedItem, type IssuerSignedItemEncodedStructure } from './issuer-signed-item'\n\nexport const issuerNamespacesEncodedSchema = z.map(z.string(), z.array(z.instanceof(DataItem)))\nexport const issuerNamespacesDecodedSchema = z.map(z.string(), z.array(z.instanceof(IssuerSignedItem)))\n\nexport type IssuerNamespacesEncodedStructure = z.infer<typeof issuerNamespacesEncodedSchema>\nexport type IssuerNamespacesDecodedStructure = z.infer<typeof issuerNamespacesDecodedSchema>\n\nexport type IssuerNamespacesOptions = {\n issuerNamespaces: IssuerNamespacesDecodedStructure\n}\n\nexport class IssuerNamespaces extends CborStructure<\n IssuerNamespacesEncodedStructure,\n IssuerNamespacesDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(issuerNamespacesEncodedSchema, issuerNamespacesDecodedSchema, {\n decode: (encoded) => {\n const issuerNamespaces = new Map<string, IssuerSignedItem[]>()\n encoded.forEach((value, key) => {\n issuerNamespaces.set(\n key,\n value.map((isi) => IssuerSignedItem.fromEncodedStructure(isi.data as IssuerSignedItemEncodedStructure))\n )\n })\n\n return issuerNamespaces\n },\n encode: (decoded) => {\n const issuerNamespaces = new Map()\n decoded.forEach((value, key) => {\n issuerNamespaces.set(\n key,\n value.map((isi) => DataItem.fromData(isi.encodedStructure))\n )\n })\n return issuerNamespaces\n },\n })\n }\n\n public get issuerNamespaces() {\n return this.structure\n }\n\n public getIssuerNamespace(namespace: string) {\n return this.structure.get(namespace)\n }\n\n public setIssuerNamespace(namespace: string, issuerSignedItems: IssuerSignedItem[]) {\n return this.structure.set(namespace, issuerSignedItems)\n }\n\n public static create(options: IssuerNamespacesOptions) {\n return this.fromDecodedStructure(options.issuerNamespaces)\n }\n}\n","import type { DocRequest } from '../mdoc/models/doc-request'\nimport { IssuerNamespaces } from '../mdoc/models/issuer-namespaces'\nimport type { IssuerSigned } from '../mdoc/models/issuer-signed'\nimport type { IssuerSignedItem } from '../mdoc/models/issuer-signed-item'\nimport type { Namespace } from '../mdoc/models/namespace'\n\nexport const limitDisclosureToDeviceRequestNameSpaces = (\n issuerSigned: IssuerSigned,\n docRequest: DocRequest\n): IssuerNamespaces => {\n const issuerNamespaces = new Map<Namespace, Array<IssuerSignedItem>>()\n for (const [namespace, nameSpaceFields] of docRequest.itemsRequest.namespaces.entries()) {\n const nsAttrs = issuerSigned.issuerNamespaces?.issuerNamespaces.get(namespace) ?? []\n const issuerSignedItems = Array.from(nameSpaceFields.entries()).map(([elementIdentifier, _]) => {\n const issuerSignedItem = prepareIssuerSignedItem(elementIdentifier, nsAttrs)\n\n if (!issuerSignedItem) {\n throw new Error(`No matching field found for '${elementIdentifier}'`)\n }\n return issuerSignedItem\n })\n issuerNamespaces.set(namespace, issuerSignedItems)\n }\n\n return IssuerNamespaces.create({ issuerNamespaces })\n}\n\nconst prepareIssuerSignedItem = (\n elementIdentifier: string,\n nsAttrs: Array<IssuerSignedItem>\n): IssuerSignedItem | null => {\n if (elementIdentifier.startsWith('age_over_')) {\n const digest = handleAgeOverNN(elementIdentifier, nsAttrs)\n return digest\n }\n\n const digest = nsAttrs.find((d) => d.elementIdentifier === elementIdentifier)\n return digest ?? null\n}\n\nconst handleAgeOverNN = (request: string, attributes: IssuerSignedItem[]): IssuerSignedItem | null => {\n const ageOverList = attributes\n .map((a, i) => {\n const { elementIdentifier: key, elementValue: value } = a\n return { key, value, index: i }\n })\n .filter((i) => i.key.startsWith('age_over_'))\n .map((i) => ({\n nn: Number.parseInt(i.key.replace('age_over_', ''), 10),\n ...i,\n }))\n .sort((a, b) => a.nn - b.nn)\n\n const reqNN = Number.parseInt(request.replace('age_over_', ''), 10)\n\n let item: (typeof ageOverList)[number] | undefined\n // Find nearest TRUE\n item = ageOverList.find((i) => i.value === true && i.nn >= reqNN)\n\n if (!item) {\n // Find the nearest False\n item = ageOverList.sort((a, b) => b.nn - a.nn).find((i) => i.value === false && i.nn <= reqNN)\n }\n\n if (!item) {\n return null\n }\n\n return attributes[item.index]\n}\n","import type { IssuerSigned } from '../mdoc'\nimport type { DocRequest } from '../mdoc/models/doc-request'\nimport { findIssuerSigned } from './findIssuerSigned'\n\nexport const verifyDocRequestsWithIssuerSigned = (docRequests: Array<DocRequest>, is: Array<IssuerSigned>) => {\n for (const docRequest of docRequests) {\n const issuerSigned = findIssuerSigned(is, docRequest.itemsRequest.docType)\n for (const [namespace, values] of docRequest.itemsRequest.namespaces) {\n const issuerSignedItems = issuerSigned.getIssuerNamespace(namespace)\n if (!issuerSignedItems) {\n throw new Error(`Could not find issuer namespace for the requested namespace '${namespace}'`)\n }\n for (const identifier of values.keys()) {\n const issuerSignedItem = issuerSignedItems.find((isi) => isi.elementIdentifier === identifier)\n if (!issuerSignedItem) {\n throw new Error(\n `Found issuer namespace '${namespace}', but could not find the element for identifier '${identifier}'`\n )\n }\n }\n }\n }\n}\n","import { z } from 'zod'\nimport { CborStructure, DataItem } from '../../cbor'\nimport { TypedMap, typedMap } from '../../utils'\nimport { DeviceAuth, type DeviceAuthEncodedStructure } from './device-auth'\nimport { DeviceNamespaces, type DeviceNamespacesEncodedStructure } from './device-namespaces'\n\nconst deviceSignedSchema = typedMap([\n ['nameSpaces', z.instanceof(DeviceNamespaces)],\n ['deviceAuth', z.instanceof(DeviceAuth)],\n] as const)\n\nexport type DeviceSignedDecodedStructure = z.output<typeof deviceSignedSchema>\nexport type DeviceSignedEncodedStructure = z.input<typeof deviceSignedSchema>\n\nexport type DeviceSignedOptions = {\n deviceNamespaces: DeviceNamespaces\n deviceAuth: DeviceAuth\n}\n\nexport class DeviceSigned extends CborStructure<DeviceSignedEncodedStructure, DeviceSignedDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(deviceSignedSchema.in, deviceSignedSchema.out, {\n decode: (input) => {\n const map: DeviceSignedDecodedStructure = TypedMap.fromMap(input)\n\n const nameSpaces = input.get('nameSpaces') as DataItem\n map.set(\n 'nameSpaces',\n DeviceNamespaces.fromEncodedStructure(nameSpaces.data as DeviceNamespacesEncodedStructure)\n )\n map.set('deviceAuth', DeviceAuth.fromEncodedStructure(input.get('deviceAuth') as DeviceAuthEncodedStructure))\n\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n map.set('nameSpaces', DataItem.fromData(output.get('nameSpaces').encodedStructure))\n map.set('deviceAuth', output.get('deviceAuth').encodedStructure)\n\n return map\n },\n })\n }\n\n public get deviceNamespaces() {\n return this.structure.get('nameSpaces')\n }\n\n public get deviceAuth() {\n return this.structure.get('deviceAuth')\n }\n\n public static create(options: DeviceSignedOptions): DeviceSigned {\n const map: DeviceSignedDecodedStructure = new TypedMap([\n ['nameSpaces', options.deviceNamespaces],\n ['deviceAuth', options.deviceAuth],\n ])\n return this.fromDecodedStructure(map)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { typedMap } from '../../utils'\n\n// Zod schema for ValidityInfo validation\n// The CBOR date extension (tag 0) handles Date <-> ISO string conversion automatically\n// So we just use z.date() and let CBOR handle the encoding/decoding\nconst validityInfoSchema = typedMap([\n ['signed', z.date()],\n ['validFrom', z.date()],\n ['validUntil', z.date()],\n ['expectedUpdate', z.date().exactOptional()],\n])\n\n// Infer structure type from Zod schema (this is the output type after decoding)\nexport type ValidityInfoEncodedStructure = z.input<typeof validityInfoSchema>\nexport type ValidityInfoDecodedStructure = z.output<typeof validityInfoSchema>\n\n// Manual options type (user-facing API)\nexport type ValidityInfoOptions = {\n signed: Date\n validFrom: Date\n validUntil: Date\n expectedUpdate?: Date\n}\n\nexport class ValidityInfo extends CborStructure<ValidityInfoEncodedStructure, ValidityInfoDecodedStructure> {\n public static override get encodingSchema() {\n return validityInfoSchema\n }\n\n public get signed() {\n return this.structure.get('signed')\n }\n\n public get validFrom() {\n return this.structure.get('validFrom')\n }\n\n public get validUntil() {\n return this.structure.get('validUntil')\n }\n\n public get expectedUpdate() {\n return this.structure.get('expectedUpdate')\n }\n\n public isSignedBetweenDates(notBefore: Date, notAfter: Date, skewSeconds = 30): boolean {\n const skewMs = skewSeconds * 1000\n const notBeforeWithSkew = new Date(notBefore.getTime() - skewMs)\n const notAfterWithSkew = new Date(notAfter.getTime() + skewMs)\n const isWithinRange = this.signed > notBeforeWithSkew && this.signed < notAfterWithSkew\n return isWithinRange\n }\n\n public isValidUntilAfterNow(now: Date = new Date(), skewSeconds = 30): boolean {\n const skewMs = skewSeconds * 1000\n const validUntilWithSkew = new Date(this.validUntil.getTime() + skewMs)\n return validUntilWithSkew >= now\n }\n\n public isValidFromBeforeNow(now: Date = new Date(), skewSeconds = 30): boolean {\n const skewMs = skewSeconds * 1000\n const validFromWithSkew = new Date(this.validFrom.getTime() - skewMs)\n return validFromWithSkew <= now\n }\n\n public static create(options: ValidityInfoOptions): ValidityInfo {\n const encodedStructure = new Map([\n ['signed', options.signed],\n ['validFrom', options.validFrom],\n ['validUntil', options.validUntil],\n ])\n\n if (options.expectedUpdate !== undefined) {\n encodedStructure.set('expectedUpdate', options.expectedUpdate)\n }\n\n return this.fromEncodedStructure(encodedStructure)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure'\nimport { zUint8Array } from '../../utils/zod'\nimport type { DigestId } from './digest-id'\nimport type { Namespace } from './namespace'\n\n// ValueDigests: Map<Namespace, Map<DigestId, Digest>>\n// Using nested Maps because DigestId is a number (integer key)\n// Maps with integer keys always stay as Maps, even when parent uses mapsAsObjects: true\n\n// Zod codec for ValueDigests\n// When parent uses mapsAsObjects: true, ALL maps become objects (even with integer keys!)\nconst valueDigestsSchema = z.map(z.string(), z.map(z.number(), zUint8Array))\n\nexport type ValueDigestsStructure = z.infer<typeof valueDigestsSchema>\n\nexport type ValueDigestOptions = {\n digests: ValueDigestsStructure\n}\n\nexport class ValueDigests extends CborStructure<ValueDigestsStructure> {\n public static override get encodingSchema() {\n return valueDigestsSchema\n }\n\n public get valueDigests() {\n return this.structure\n }\n\n public static create(options: ValueDigestOptions) {\n return this.fromEncodedStructure(options.digests)\n }\n\n public getDigestForNamespace(namespace: Namespace, digestId: DigestId) {\n return this.structure.get(namespace)?.get(digestId)\n }\n\n public hasDigestForNamespace(namespace: Namespace, digestId: DigestId) {\n return this.structure.get(namespace)?.has(digestId) ?? false\n }\n\n public getNamespaces(): Namespace[] {\n return Array.from(this.structure.keys())\n }\n\n public getDigestIdsForNamespace(namespace: Namespace): DigestId[] {\n const namespaceDigests = this.structure.get(namespace)\n if (!namespaceDigests) {\n return []\n }\n return Array.from(namespaceDigests.keys())\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport type { DigestAlgorithm } from '../../cose'\nimport { TypedMap, typedMap } from '../../utils'\nimport { DeviceKeyInfo, type DeviceKeyInfoEncodedStructure } from './device-key-info'\nimport type { DocType } from './doctype'\nimport { ValidityInfo, type ValidityInfoEncodedStructure } from './validity-info'\nimport { ValueDigests, type ValueDigestsStructure } from './value-digests'\n\n// Zod schema for MobileSecurityObject\n// MSO has string keys, so we use z.object and set mapsAsObjects: true\nconst mobileSecurityObjectSchema = typedMap([\n // mDOC only defines 1.0\n ['version', z.literal('1.0')],\n ['digestAlgorithm', z.enum(['SHA-256', 'SHA-384', 'SHA-512'])],\n ['docType', z.string()],\n ['valueDigests', z.instanceof(ValueDigests)],\n ['deviceKeyInfo', z.instanceof(DeviceKeyInfo)],\n ['validityInfo', z.instanceof(ValidityInfo)],\n])\n\nexport type MobileSecurityObjectDecodedStructure = z.output<typeof mobileSecurityObjectSchema>\nexport type MobileSecurityObjectEncodedStructure = z.input<typeof mobileSecurityObjectSchema>\n\nexport type MobileSecurityObjectOptions = {\n version?: '1.0'\n digestAlgorithm: DigestAlgorithm\n docType: DocType\n valueDigests: ValueDigests\n validityInfo: ValidityInfo\n deviceKeyInfo: DeviceKeyInfo\n}\n\nexport class MobileSecurityObject extends CborStructure<\n MobileSecurityObjectEncodedStructure,\n MobileSecurityObjectDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(mobileSecurityObjectSchema.in, mobileSecurityObjectSchema.out, {\n decode: (input) => {\n const map: MobileSecurityObjectDecodedStructure = TypedMap.fromMap(input)\n\n // Need to transform into class types\n map.set('valueDigests', ValueDigests.fromEncodedStructure(input.get('valueDigests') as ValueDigestsStructure))\n map.set(\n 'deviceKeyInfo',\n DeviceKeyInfo.fromEncodedStructure(input.get('deviceKeyInfo') as DeviceKeyInfoEncodedStructure)\n )\n map.set(\n 'validityInfo',\n ValidityInfo.fromEncodedStructure(input.get('validityInfo') as ValidityInfoEncodedStructure)\n )\n\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n\n // Need to transform into class encoded structure types\n map.set('valueDigests', output.get('valueDigests').encodedStructure)\n map.set('deviceKeyInfo', output.get('deviceKeyInfo').encodedStructure)\n map.set('validityInfo', output.get('validityInfo').encodedStructure)\n\n return map\n },\n })\n }\n\n public get version() {\n return this.structure.get('version')\n }\n\n public get digestAlgorithm() {\n return this.structure.get('digestAlgorithm')\n }\n\n public get docType() {\n return this.structure.get('docType')\n }\n\n public get validityInfo() {\n return this.structure.get('validityInfo')\n }\n\n public get valueDigests() {\n return this.structure.get('valueDigests')\n }\n\n public get deviceKeyInfo() {\n return this.structure.get('deviceKeyInfo')\n }\n\n public static create(options: MobileSecurityObjectOptions): MobileSecurityObject {\n // Property order MUST match spec: version, digestAlgorithm, valueDigests, deviceKeyInfo, docType, validityInfo\n const map: MobileSecurityObjectDecodedStructure = new TypedMap([\n ['version', options.version ?? '1.0'],\n ['digestAlgorithm', options.digestAlgorithm],\n ['valueDigests', options.valueDigests],\n ['deviceKeyInfo', options.deviceKeyInfo],\n ['docType', options.docType],\n ['validityInfo', options.validityInfo],\n ])\n\n return this.fromDecodedStructure(map)\n }\n}\n","import z from 'zod'\nimport { cborDecode, DataItem } from '../../cbor/index.js'\nimport type { MdocContext } from '../../context.js'\nimport { CosePayloadMustBeDefinedError } from '../../cose/error.js'\nimport { Sign1, type Sign1EncodedStructure, type Sign1Options } from '../../cose/sign1.js'\nimport { zUint8Array } from '../../utils/zod.js'\nimport { defaultVerificationCallback, onCategoryCheck, type VerificationCallback } from '../check-callback.js'\nimport { MobileSecurityObject, type MobileSecurityObjectEncodedStructure } from './mobile-security-object.js'\n\nexport type IssuerAuthEncodedStructure = Sign1EncodedStructure\nexport type IssuerAuthOptions = Omit<Sign1Options, 'payload'> & {\n payload?: Sign1Options['payload'] | MobileSecurityObject\n}\n\nexport class IssuerAuth extends Sign1 {\n public static create(options: IssuerAuthOptions, ctx: Pick<MdocContext, 'cose'>): Promise<IssuerAuth> {\n return super.create(\n {\n ...options,\n payload:\n options.payload instanceof MobileSecurityObject\n ? options.payload.encode({ asDataItem: true })\n : options.payload,\n },\n ctx\n ) as Promise<IssuerAuth>\n }\n\n // NOTE: currently lazy loaded and validated, but i think that's fine?\n public get mobileSecurityObject(): MobileSecurityObject {\n if (!this.payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n const mso = zUint8Array\n .transform((payload) =>\n cborDecode(payload, {\n unwrapTopLevelDataItem: false,\n })\n )\n .pipe(\n z\n .instanceof<typeof DataItem<MobileSecurityObjectEncodedStructure>>(DataItem)\n .transform((di) => MobileSecurityObject.fromEncodedStructure(di.data))\n )\n .parse(this.payload)\n\n return mso\n }\n\n public async verify(\n options: {\n verificationCallback?: VerificationCallback\n now?: Date\n trustedCertificates?: Array<Uint8Array>\n disableCertificateChainValidation?: boolean\n skewSeconds?: number\n },\n ctx: Pick<MdocContext, 'x509' | 'cose'>\n ) {\n const verificationCallback = options.verificationCallback ?? defaultVerificationCallback\n const now = options.now ?? new Date()\n const disableCertificateChainValidation = options.disableCertificateChainValidation ?? false\n const trustedCertificates = options.trustedCertificates ?? []\n const skewSeconds = options.skewSeconds ?? 30\n\n const onCheck = onCategoryCheck(verificationCallback, 'ISSUER_AUTH')\n\n onCheck({\n status: this.getIssuingCountry(ctx) ? 'PASSED' : 'FAILED',\n check: \"Country name (C) must be present in the issuer certificate's subject distinguished name\",\n })\n\n if (!disableCertificateChainValidation) {\n try {\n if (!trustedCertificates[0]) {\n throw new Error('No trusted certificates found. Cannot verify issuer signature.')\n }\n\n await ctx.x509.verifyCertificateChain({\n trustedCertificates,\n x5chain: this.certificateChain,\n now,\n })\n\n onCheck({\n status: 'PASSED',\n check: 'Issuer certificate must be valid',\n })\n } catch (err) {\n onCheck({\n status: 'FAILED',\n check: 'Issuer certificate must be valid',\n reason: err instanceof Error ? err.message : 'Unknown error',\n })\n }\n }\n\n const isSignatureValid = await this.verifySignature({}, ctx)\n\n onCheck({\n status: isSignatureValid ? 'PASSED' : 'FAILED',\n check: 'Issuer auth signature is invalid',\n })\n\n const { validityInfo } = this.mobileSecurityObject\n\n const { notAfter, notBefore } = await ctx.x509.getCertificateData({\n certificate: this.certificate,\n })\n\n onCheck({\n status: validityInfo.isSignedBetweenDates(notBefore, notAfter, skewSeconds) ? 'PASSED' : 'FAILED',\n check: 'The MSO signed date must be within the validity period of the certificate',\n reason: `The MSO signed date (${validityInfo.signed.toUTCString()}) must be within the validity period of the certificate (${notBefore.toUTCString()} to ${notAfter.toUTCString()})`,\n })\n\n onCheck({\n status:\n validityInfo.isValidFromBeforeNow(now, skewSeconds) && validityInfo.isValidUntilAfterNow(now, skewSeconds)\n ? 'PASSED'\n : 'FAILED',\n check: 'The MSO must be valid at the time of verification',\n reason: `The MSO must be valid at the time of verification (${now.toUTCString()})`,\n })\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport type { MdocContext } from '../../context'\nimport { base64url, TypedMap, typedMap } from '../../utils'\nimport { defaultVerificationCallback, onCategoryCheck, type VerificationCallback } from '../check-callback'\nimport { IssuerAuth, type IssuerAuthEncodedStructure } from './issuer-auth'\nimport { IssuerNamespaces, type IssuerNamespacesEncodedStructure } from './issuer-namespaces'\nimport type { IssuerSignedItem } from './issuer-signed-item'\nimport type { Namespace } from './namespace'\n\nconst issuerSignedSchema = typedMap([\n ['nameSpaces', z.instanceof(IssuerNamespaces)],\n ['issuerAuth', z.instanceof(IssuerAuth)],\n])\n\nexport type IssuerSignedDecodedStructure = z.output<typeof issuerSignedSchema>\nexport type IssuerSignedEncodedStructure = z.input<typeof issuerSignedSchema>\n\nexport type IssuerSignedOptions = {\n issuerNamespaces?: IssuerNamespaces\n issuerAuth: IssuerAuth\n}\n\nexport class IssuerSigned extends CborStructure<IssuerSignedEncodedStructure, IssuerSignedDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(issuerSignedSchema.in, issuerSignedSchema.out, {\n decode: (input) => {\n const map: IssuerSignedDecodedStructure = TypedMap.fromMap(input)\n\n // Need to transform namespace into class type\n map.set(\n 'nameSpaces',\n IssuerNamespaces.fromEncodedStructure(input.get('nameSpaces') as IssuerNamespacesEncodedStructure)\n )\n\n // Need to transform namespace into class type\n map.set('issuerAuth', IssuerAuth.fromEncodedStructure(input.get('issuerAuth') as IssuerAuthEncodedStructure))\n\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n map.set('nameSpaces', output.get('nameSpaces').encodedStructure)\n map.set('issuerAuth', output.get('issuerAuth').encodedStructure)\n\n return map\n },\n })\n }\n\n public get issuerNamespaces() {\n return this.structure.get('nameSpaces')\n }\n\n public get issuerAuth() {\n return this.structure.get('issuerAuth')\n }\n\n public getIssuerNamespace(namespace: Namespace) {\n return this.issuerNamespaces.getIssuerNamespace(namespace)\n }\n\n public getPrettyClaims(namespace: Namespace) {\n const issuerSignedItems = this.getIssuerNamespace(namespace)\n if (!issuerSignedItems) return undefined\n\n return issuerSignedItems.reduce((prev, curr) => ({ ...prev, [curr.elementIdentifier]: curr.elementValue }), {})\n }\n\n public get encodedForOid4Vci() {\n return base64url.encode(this.encode())\n }\n\n public static fromEncodedForOid4Vci(encoded: string): IssuerSigned {\n return this.decode(base64url.decode(encoded)) as IssuerSigned\n }\n\n public async verify(\n options: { verificationCallback?: VerificationCallback },\n ctx: Pick<MdocContext, 'x509' | 'crypto'>\n ) {\n const { valueDigests, digestAlgorithm } = this.issuerAuth.mobileSecurityObject\n\n const onCheck = onCategoryCheck(options.verificationCallback ?? defaultVerificationCallback, 'DATA_INTEGRITY')\n\n onCheck({\n status: digestAlgorithm ? 'PASSED' : 'FAILED',\n check: 'Issuer Auth must include a supported digestAlgorithm element',\n })\n\n const namespaces = this.issuerNamespaces?.issuerNamespaces ?? new Map<string, IssuerSignedItem[]>()\n\n await Promise.all(\n Array.from(namespaces.entries()).map(async ([ns, nsItems]) => {\n onCheck({\n status: valueDigests?.valueDigests.has(ns) ? 'PASSED' : 'FAILED',\n check: `Issuer Auth must include digests for namespace: ${ns}`,\n })\n\n const verifications = await Promise.all(\n nsItems.map(async (ev) => {\n const isValid = await ev.isValid(ns, this.issuerAuth, ctx)\n return { ev, ns, isValid }\n })\n )\n\n for (const verification of verifications.filter((v) => v.isValid)) {\n onCheck({\n status: 'PASSED',\n check: `The calculated digest for ${ns}/${verification.ev.elementIdentifier} attribute must match the digest in the issuerAuth element`,\n })\n }\n\n for (const verification of verifications.filter((v) => !v.isValid)) {\n onCheck({\n status: 'FAILED',\n check: `The calculated digest for ${ns}/${verification.ev.elementIdentifier} attribute must match the digest in the issuerAuth element`,\n })\n }\n\n if (ns === 'org.iso.18013.5.1') {\n const certificateData = await ctx.x509.getCertificateData({\n certificate: this.issuerAuth.certificate,\n })\n if (!certificateData.issuerName) {\n onCheck({\n status: 'FAILED',\n check:\n \"The 'issuing_country' if present must match the 'countryName' in the subject field within the DS certificate\",\n reason:\n \"The 'issuing_country' and 'issuing_jurisdiction' cannot be verified because the DS certificate was not provided\",\n })\n } else {\n const invalidCountry = verifications\n .filter((v) => v.ns === ns && v.ev.elementIdentifier === 'issuing_country')\n .find((v) => !v.isValid || !v.ev.matchCertificate(this.issuerAuth, ctx))\n\n onCheck({\n status: invalidCountry ? 'FAILED' : 'PASSED',\n check:\n \"The 'issuing_country' if present must match the 'countryName' in the subject field within the DS certificate\",\n reason: invalidCountry\n ? `The 'issuing_country' (${invalidCountry.ev.elementValue}) must match the 'countryName' (${this.issuerAuth.getIssuingCountry(ctx)}) in the subject field within the issuer certificate`\n : undefined,\n })\n\n const invalidJurisdiction = verifications\n .filter((v) => v.ns === ns && v.ev.elementIdentifier === 'issuing_jurisdiction')\n .find((v) => !v.isValid || !v.ev.matchCertificate(this.issuerAuth, ctx))\n\n onCheck({\n status: invalidJurisdiction ? 'FAILED' : 'PASSED',\n check:\n \"The 'issuing_jurisdiction' if present must match the 'stateOrProvinceName' in the subject field within the DS certificate\",\n reason: invalidJurisdiction\n ? `The 'issuing_jurisdiction' (${invalidJurisdiction.ev.elementValue}) must match the 'stateOrProvinceName' (${this.issuerAuth.getIssuingStateOrProvince(ctx)}) in the subject field within the issuer certificate`\n : undefined,\n })\n }\n }\n })\n )\n }\n\n public static create(options: IssuerSignedOptions): IssuerSigned {\n const map: IssuerSignedDecodedStructure = new TypedMap([])\n\n if (options.issuerNamespaces) {\n map.set('nameSpaces', options.issuerNamespaces)\n }\n\n map.set('issuerAuth', options.issuerAuth)\n\n return this.fromDecodedStructure(map)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { TypedMap, typedMap } from '../../utils'\nimport { DeviceSigned, type DeviceSignedEncodedStructure } from './device-signed'\nimport type { DocType } from './doctype'\nimport type { ErrorItems } from './error-items'\nimport { IssuerSigned, type IssuerSignedEncodedStructure } from './issuer-signed'\nimport type { Namespace } from './namespace'\n\nconst documentSchema = typedMap([\n ['docType', z.string()],\n ['issuerSigned', z.instanceof(IssuerSigned)],\n ['deviceSigned', z.instanceof(DeviceSigned)],\n ['errors', z.map(z.string(), z.unknown()).exactOptional()],\n] as const)\n\nexport type DocumentDecodedStructure = z.output<typeof documentSchema>\nexport type DocumentEncodedStructure = z.input<typeof documentSchema>\n\nexport type DocumentOptions = {\n docType: DocType\n issuerSigned: IssuerSigned\n deviceSigned: DeviceSigned\n errors?: Map<Namespace, ErrorItems>\n}\n\nexport class Document extends CborStructure<DocumentEncodedStructure, DocumentDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(documentSchema.in, documentSchema.out, {\n decode: (input) => {\n const map: DocumentDecodedStructure = TypedMap.fromMap(input)\n\n map.set(\n 'issuerSigned',\n IssuerSigned.fromEncodedStructure(input.get('issuerSigned') as IssuerSignedEncodedStructure)\n )\n map.set(\n 'deviceSigned',\n DeviceSigned.fromEncodedStructure(input.get('deviceSigned') as DeviceSignedEncodedStructure)\n )\n\n if (input.has('errors')) {\n map.set('errors', input.get('errors') as Map<string, unknown>)\n }\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n map.set('issuerSigned', output.get('issuerSigned').encodedStructure)\n map.set('deviceSigned', output.get('deviceSigned').encodedStructure)\n\n return map\n },\n })\n }\n\n public get docType() {\n return this.structure.get('docType')\n }\n\n public get issuerSigned() {\n return this.structure.get('issuerSigned')\n }\n\n public get deviceSigned() {\n return this.structure.get('deviceSigned')\n }\n\n public get errors() {\n return this.structure.get('errors')\n }\n\n public getIssuerNamespace(namespace: Namespace) {\n const issuerSigned = this.structure.get('issuerSigned')\n const issuerNamespaces = issuerSigned?.issuerNamespaces?.issuerNamespaces\n\n if (!issuerNamespaces) {\n return undefined\n }\n\n return issuerNamespaces.get(namespace)\n }\n\n public static create(options: DocumentOptions): Document {\n const map: DocumentDecodedStructure = new TypedMap([\n ['docType', options.docType],\n ['issuerSigned', options.issuerSigned],\n ['deviceSigned', options.deviceSigned],\n ])\n if (options.errors) {\n map.set('errors', options.errors)\n }\n return this.fromDecodedStructure(map)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\n\n// Zod schema for DocumentError\nconst documentErrorSchema = z.map(z.string(), z.number())\n\nexport type DocumentErrorStructure = z.infer<typeof documentErrorSchema>\n\nexport type DocumentErrorOptions = {\n documentError: DocumentErrorStructure\n}\n\nexport class DocumentError extends CborStructure<DocumentErrorStructure> {\n public static override get encodingSchema() {\n return documentErrorSchema\n }\n\n /**\n * Map where keys are namespaces and values are error codes\n */\n public get documentError() {\n return this.structure\n }\n\n public static create(options: DocumentErrorOptions): DocumentError {\n return new DocumentError(options.documentError)\n }\n}\n","import { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport type { MdocContext } from '../../context'\nimport { type CoseKey, Header, ProtectedHeaders, UnprotectedHeaders } from '../../cose'\nimport { base64url, TypedMap, typedMap } from '../../utils'\nimport { findIssuerSigned } from '../../utils/findIssuerSigned'\nimport { limitDisclosureToDeviceRequestNameSpaces } from '../../utils/limitDisclosure'\nimport { verifyDocRequestsWithIssuerSigned } from '../../utils/verifyDocRequestsWithIssuerSigned'\nimport { defaultVerificationCallback, type VerificationCallback } from '../check-callback'\nimport { EitherSignatureOrMacMustBeProvidedError } from '../errors'\nimport { DeviceAuth, type DeviceAuthOptions } from './device-auth'\nimport { DeviceAuthentication } from './device-authentication'\nimport { DeviceMac } from './device-mac'\nimport { DeviceNamespaces } from './device-namespaces'\nimport type { DeviceRequest } from './device-request'\nimport { DeviceSignature } from './device-signature'\nimport { DeviceSigned } from './device-signed'\nimport { Document, type DocumentEncodedStructure } from './document'\nimport { DocumentError, type DocumentErrorStructure } from './document-error'\nimport { IssuerSigned } from './issuer-signed'\nimport type { SessionTranscript } from './session-transcript'\n\nconst deviceResponseEncodedSchema = typedMap([\n ['version', z.string()],\n ['status', z.number()],\n ['documents', z.array(z.unknown()).exactOptional()],\n ['documentErrors', z.array(z.unknown()).exactOptional()],\n] as const)\n\nconst deviceResponseDecodedSchema = typedMap([\n ['version', z.string()],\n ['status', z.number()],\n ['documents', z.array(z.instanceof(Document)).exactOptional()],\n ['documentErrors', z.array(z.instanceof(DocumentError)).exactOptional()],\n] as const)\n\nexport type DeviceResponseEncodedStructure = z.input<typeof deviceResponseEncodedSchema>\nexport type DeviceResponseDecodedStructure = z.output<typeof deviceResponseDecodedSchema>\n\nexport type DeviceResponseOptions = {\n version?: string\n documents?: Array<Document>\n documentErrors?: Array<DocumentError>\n status?: number\n}\n\nexport class DeviceResponse extends CborStructure<DeviceResponseEncodedStructure, DeviceResponseDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(deviceResponseEncodedSchema.in, deviceResponseDecodedSchema.out, {\n decode: (input) => {\n const map = TypedMap.fromMap(input) as DeviceResponseDecodedStructure\n\n if (input.has('documents')) {\n map.set(\n 'documents',\n (input.get('documents') as unknown[]).map((d) =>\n Document.fromEncodedStructure(d as DocumentEncodedStructure)\n )\n )\n }\n\n if (input.has('documentErrors')) {\n map.set(\n 'documentErrors',\n (input.get('documentErrors') as unknown[]).map((d) =>\n DocumentError.fromEncodedStructure(d as DocumentErrorStructure)\n )\n )\n }\n\n return map\n },\n encode: (output) => {\n const map: Map<unknown, unknown> = output.toMap()\n\n const documents = output.get('documents')\n if (documents !== undefined) {\n map.set(\n 'documents',\n documents.map((d) => d.encodedStructure)\n )\n }\n\n const documentErrors = output.get('documentErrors')\n if (documentErrors !== undefined) {\n map.set(\n 'documentErrors',\n documentErrors.map((d) => d.encodedStructure)\n )\n }\n\n return map\n },\n })\n }\n\n public get version() {\n return this.structure.get('version')\n }\n\n public get documents() {\n return this.structure.get('documents')\n }\n\n public get documentErrors() {\n return this.structure.get('documentErrors')\n }\n\n public get status() {\n return this.structure.get('status')\n }\n\n public async verify(\n options: {\n deviceRequest?: DeviceRequest\n sessionTranscript: SessionTranscript | Uint8Array\n ephemeralReaderKey?: CoseKey\n disableCertificateChainValidation?: boolean\n trustedCertificates: Uint8Array[]\n now?: Date\n onCheck?: VerificationCallback\n skewSeconds?: number\n },\n ctx: Pick<MdocContext, 'cose' | 'x509' | 'crypto'>\n ) {\n const onCheck = options.onCheck ?? defaultVerificationCallback\n\n const version = this.structure.get('version')\n onCheck({\n status: version ? 'PASSED' : 'FAILED',\n check: 'Device Response must include \"version\" element.',\n category: 'DOCUMENT_FORMAT',\n })\n\n const documents = this.structure.get('documents')\n onCheck({\n status: !documents || documents.length > 0 ? 'PASSED' : 'FAILED',\n check: 'Device Response must not include documents or at least one document.',\n category: 'DOCUMENT_FORMAT',\n })\n\n for (const document of documents ?? []) {\n await document.issuerSigned.issuerAuth.verify(\n {\n disableCertificateChainValidation: options.disableCertificateChainValidation,\n now: options.now,\n trustedCertificates: options.trustedCertificates,\n verificationCallback: onCheck,\n skewSeconds: options.skewSeconds,\n },\n ctx\n )\n\n await document.deviceSigned.deviceAuth.verify(\n {\n document,\n ephemeralMacPrivateKey: options.ephemeralReaderKey,\n sessionTranscript: options.sessionTranscript,\n verificationCallback: onCheck,\n },\n ctx\n )\n\n await document.issuerSigned.verify({ verificationCallback: onCheck }, ctx)\n }\n\n if (options.deviceRequest?.docRequests && documents) {\n try {\n verifyDocRequestsWithIssuerSigned(\n options.deviceRequest.docRequests,\n documents.map((d) => d.issuerSigned)\n )\n onCheck({\n status: 'PASSED',\n check: 'Device Response did match the Device Request',\n category: 'DOCUMENT_FORMAT',\n })\n } catch (e) {\n onCheck({\n status: 'FAILED',\n check: `Device Response did not match the Device Request: ${(e as Error).message}`,\n category: 'DOCUMENT_FORMAT',\n })\n }\n }\n }\n\n public get encodedForOid4Vp() {\n return base64url.encode(this.encode())\n }\n\n public static fromEncodedForOid4Vp(encoded: string): DeviceResponse {\n return DeviceResponse.decode(base64url.decode(encoded))\n }\n\n private static async create(\n options: {\n deviceRequest: DeviceRequest\n sessionTranscript: SessionTranscript | Uint8Array\n issuerSigned: Array<IssuerSigned>\n deviceNamespaces?: DeviceNamespaces\n signature?: {\n signingKey: CoseKey\n }\n mac?: {\n ephemeralKey: CoseKey\n signingKey: CoseKey\n }\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose'>\n ) {\n const useMac = !!options.mac\n const useSignature = !!options.signature\n if (useMac === useSignature) throw new EitherSignatureOrMacMustBeProvidedError()\n\n const signingKey = useSignature ? options.signature?.signingKey : options.mac?.signingKey\n if (!signingKey) throw new Error('Signing key is missing')\n\n const documents = await Promise.all(\n options.deviceRequest.docRequests.map(async (docRequest) => {\n const issuerSigned = findIssuerSigned(options.issuerSigned, docRequest.itemsRequest.docType)\n const disclosedIssuerNamespace = limitDisclosureToDeviceRequestNameSpaces(issuerSigned, docRequest)\n\n const docType = docRequest.itemsRequest.docType\n\n const deviceNamespaces = options.deviceNamespaces ?? DeviceNamespaces.create({ deviceNamespaces: new Map() })\n\n const deviceAuthenticationBytes = DeviceAuthentication.create({\n sessionTranscript: options.sessionTranscript,\n docType,\n deviceNamespaces,\n }).encode({ asDataItem: true })\n\n const unprotectedHeaders = signingKey.keyId\n ? UnprotectedHeaders.create({ unprotectedHeaders: new Map([[Header.KeyId, signingKey.keyId]]) })\n : UnprotectedHeaders.create({})\n\n const protectedHeaders = ProtectedHeaders.create({\n protectedHeaders: new Map([[Header.Algorithm, signingKey.algorithm]]),\n })\n\n const deviceAuthOptions: DeviceAuthOptions = {}\n if (useSignature) {\n const deviceSignature = await DeviceSignature.create(\n {\n unprotectedHeaders,\n protectedHeaders,\n detachedPayload: deviceAuthenticationBytes,\n signingKey,\n },\n ctx\n )\n\n deviceAuthOptions.deviceSignature = deviceSignature\n } else {\n const ephemeralKey = options.mac?.ephemeralKey\n if (!ephemeralKey) throw new Error('Ephemeral key is missing')\n\n const deviceMac = await DeviceMac.create(\n {\n protectedHeaders,\n unprotectedHeaders,\n detachedPayload: deviceAuthenticationBytes,\n privateKey: signingKey,\n ephemeralKey: ephemeralKey,\n sessionTranscript: options.sessionTranscript,\n },\n ctx\n )\n\n deviceAuthOptions.deviceMac = deviceMac\n }\n\n return Document.create({\n docType,\n issuerSigned: IssuerSigned.create({\n issuerNamespaces: disclosedIssuerNamespace,\n issuerAuth: issuerSigned.issuerAuth,\n }),\n deviceSigned: DeviceSigned.create({\n deviceNamespaces,\n deviceAuth: DeviceAuth.create(deviceAuthOptions),\n }),\n })\n })\n )\n\n const map: DeviceResponseDecodedStructure = new TypedMap([\n ['version', '1.0'],\n ['status', 0],\n ['documents', documents],\n ])\n\n return DeviceResponse.fromDecodedStructure(map)\n }\n\n public static async createWithDeviceRequest(\n options: {\n deviceRequest: DeviceRequest\n sessionTranscript: SessionTranscript | Uint8Array\n issuerSigned: Array<IssuerSigned>\n deviceNamespaces?: DeviceNamespaces\n mac?: {\n ephemeralKey: CoseKey\n signingKey: CoseKey\n }\n signature?: {\n signingKey: CoseKey\n }\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose'>\n ) {\n return await DeviceResponse.create(options, ctx)\n }\n\n public static createSimple(options: DeviceResponseOptions): DeviceResponse {\n const map: DeviceResponseDecodedStructure = new TypedMap([\n ['version', options.version ?? '1.0'],\n ['status', options.status ?? 0],\n ])\n\n if (options.documents !== undefined) {\n map.set('documents', options.documents)\n }\n\n if (options.documentErrors !== undefined) {\n map.set('documentErrors', options.documentErrors)\n }\n\n return this.fromDecodedStructure(map)\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport type { ErrorCode } from './error-code'\n\nexport const errorItemsSchema = z.map(z.string(), z.number())\nexport type ErrorItemsStructure = Map<DataElementIdentifier, ErrorCode>\n\nexport type ErrorItemsOptions = {\n errorItems: ErrorItemsStructure\n}\n\nexport class ErrorItems extends CborStructure<ErrorItemsStructure> {\n public static override get encodingSchema() {\n return errorItemsSchema\n }\n\n public static create(options: ErrorItemsOptions) {\n return this.fromDecodedStructure(options.errorItems)\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { ErrorItems, errorItemsSchema } from './error-items'\n\nconst errorsEncodedSchema = z.map(z.string(), errorItemsSchema)\nconst errorsDecodedSchema = z.map(z.string(), z.instanceof(ErrorItems))\n\nexport type ErrorsEncodedStructure = z.infer<typeof errorsEncodedSchema>\nexport type ErrorsDecodedStructure = z.infer<typeof errorsDecodedSchema>\n\nexport type ErrorsOptions = {\n errors: ErrorsDecodedStructure\n}\n\nexport class Errors extends CborStructure<ErrorsEncodedStructure, ErrorsDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(errorsEncodedSchema, errorsDecodedSchema, {\n encode: (decoded) => {\n const errorsDecoded: ErrorsEncodedStructure = new Map()\n\n decoded.forEach((value, key) => {\n errorsDecoded.set(key, value.encodedStructure)\n })\n\n return errorsDecoded\n },\n decode: (encoded) => {\n const errorsDecoded: ErrorsDecodedStructure = new Map()\n\n encoded.forEach((value, key) => {\n errorsDecoded.set(key, ErrorItems.fromEncodedStructure(value))\n })\n\n return errorsDecoded\n },\n })\n }\n}\n","import type { MdocContext } from '../../context'\nimport {\n type CoseKey,\n Header,\n type MacAlgorithm,\n ProtectedHeaders,\n type SignatureAlgorithm,\n UnprotectedHeaders,\n} from '../../cose'\nimport { base64 } from '../../utils'\nimport {\n DeviceAuth,\n DeviceMac,\n DeviceNamespaces,\n DeviceSignature,\n DeviceSigned,\n DeviceSignedItems,\n type DocType,\n type Namespace,\n type SessionTranscript,\n} from '../models'\nimport { DeviceAuthentication } from '../models/device-authentication'\n\nexport class DeviceSignedBuilder {\n private docType: DocType\n private namespaces: DeviceNamespaces\n private ctx: Pick<MdocContext, 'cose' | 'crypto'>\n\n public constructor(docType: DocType, ctx: Pick<MdocContext, 'cose' | 'crypto'>) {\n this.docType = docType\n this.namespaces = DeviceNamespaces.create({ deviceNamespaces: new Map() })\n this.ctx = ctx\n }\n\n public addDeviceNamespace(namespace: Namespace, value: Record<string, unknown>) {\n const deviceSignedItems =\n this.namespaces.deviceNamespaces.get(namespace) ?? DeviceSignedItems.create({ deviceSignedItems: new Map() })\n\n for (const [k, v] of Object.entries(value)) {\n deviceSignedItems.deviceSignedItems.set(k, v)\n }\n\n this.namespaces.deviceNamespaces.set(namespace, deviceSignedItems)\n\n return this\n }\n\n public async sign(options: {\n signingKey: CoseKey\n algorithm: SignatureAlgorithm\n sessionTranscript: SessionTranscript\n derCertificate: string\n }): Promise<DeviceSigned> {\n const protectedHeaders = ProtectedHeaders.create({\n protectedHeaders: new Map([[Header.Algorithm, options.algorithm]]),\n })\n\n const unprotectedHeaders = UnprotectedHeaders.create({\n unprotectedHeaders: new Map([[Header.X5Chain, base64.decode(options.derCertificate)]]),\n })\n\n if (options.signingKey.keyId) {\n unprotectedHeaders.headers?.set(Header.KeyId, options.signingKey.keyId)\n }\n\n const deviceAuthentication = DeviceAuthentication.create({\n sessionTranscript: options.sessionTranscript,\n deviceNamespaces: this.namespaces,\n docType: this.docType,\n })\n\n const deviceSignature = await DeviceSignature.create(\n {\n unprotectedHeaders,\n protectedHeaders,\n detachedPayload: deviceAuthentication.encode({ asDataItem: true }),\n signingKey: options.signingKey,\n },\n this.ctx\n )\n\n return DeviceSigned.create({\n deviceNamespaces: this.namespaces,\n deviceAuth: DeviceAuth.create({\n deviceSignature,\n }),\n })\n }\n\n public async tag(options: {\n publicKey: CoseKey\n privateKey: CoseKey\n sessionTranscript: SessionTranscript\n algorithm: MacAlgorithm\n derCertificate: string\n }): Promise<DeviceSigned> {\n const protectedHeaders = ProtectedHeaders.create({\n protectedHeaders: new Map([[Header.Algorithm, options.algorithm]]),\n })\n\n const unprotectedHeaders = UnprotectedHeaders.create({\n unprotectedHeaders: new Map([[Header.X5Chain, base64.decode(options.derCertificate)]]),\n })\n\n if (options.privateKey.keyId) {\n unprotectedHeaders.headers?.set(Header.KeyId, options.privateKey.keyId)\n }\n\n const deviceAuthentication = DeviceAuthentication.create({\n sessionTranscript: options.sessionTranscript,\n deviceNamespaces: this.namespaces,\n docType: this.docType,\n })\n\n const deviceMac = await DeviceMac.create(\n {\n unprotectedHeaders,\n protectedHeaders,\n detachedPayload: deviceAuthentication.encode({ asDataItem: true }),\n privateKey: options.privateKey,\n ephemeralKey: options.publicKey,\n sessionTranscript: options.sessionTranscript,\n },\n this.ctx\n )\n\n return DeviceSigned.create({\n deviceNamespaces: this.namespaces,\n deviceAuth: DeviceAuth.create({\n deviceMac,\n }),\n })\n }\n}\n","import type { MdocContext } from '../context'\n\nexport const randomUnsignedInteger = (ctx: Pick<MdocContext, 'crypto'>) => {\n const bytes = ctx.crypto.random(4)\n return ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0\n}\n","import type { MdocContext } from '../../context'\nimport {\n type CoseKey,\n type DigestAlgorithm,\n Header,\n ProtectedHeaders,\n type SignatureAlgorithm,\n UnprotectedHeaders,\n} from '../../cose'\nimport { randomUnsignedInteger } from '../../utils/randomUnsignedInteger'\nimport {\n DeviceKeyInfo,\n type DeviceKeyInfoOptions,\n type Digest,\n type DigestId,\n type DocType,\n IssuerAuth,\n IssuerNamespaces,\n IssuerSigned,\n IssuerSignedItem,\n MobileSecurityObject,\n type Namespace,\n ValidityInfo,\n type ValidityInfoOptions,\n ValueDigests,\n type ValueDigestsStructure,\n} from '../models'\n\nexport class IssuerSignedBuilder {\n private docType: DocType\n private namespaces: IssuerNamespaces\n private ctx: Pick<MdocContext, 'cose' | 'crypto'>\n\n public constructor(docType: DocType, ctx: Pick<MdocContext, 'cose' | 'crypto'>) {\n this.docType = docType\n this.ctx = ctx\n this.namespaces = IssuerNamespaces.create({ issuerNamespaces: new Map() })\n }\n\n public addIssuerNamespace(namespace: Namespace, values: Record<string, unknown> | Map<string, unknown>) {\n const issuerNamespace = this.namespaces.getIssuerNamespace(namespace) ?? []\n\n const entries = values instanceof Map ? Array.from(values.entries()) : Object.entries(values)\n\n const issuerSignedItems = entries.map(([key, value]) =>\n IssuerSignedItem.fromOptions({\n digestId: randomUnsignedInteger(this.ctx),\n random: this.ctx.crypto.random(32),\n elementIdentifier: key,\n elementValue: value,\n })\n )\n issuerNamespace.push(...issuerSignedItems)\n\n this.namespaces.setIssuerNamespace(namespace, issuerNamespace)\n\n return this\n }\n\n private async convertIssuerNamespacesIntoValueDigests(digestAlgorithm: DigestAlgorithm): Promise<ValueDigests> {\n const valueDigests: ValueDigestsStructure = new Map()\n\n for (const [namespace, issuerSignedItems] of this.namespaces.issuerNamespaces) {\n const digests = new Map<DigestId, Digest>()\n for (const issuerSignedItem of issuerSignedItems) {\n const digest = await this.ctx.crypto.digest({\n digestAlgorithm,\n bytes: issuerSignedItem.encode({ asDataItem: true }),\n })\n\n digests.set(issuerSignedItem.digestId, digest)\n }\n valueDigests.set(namespace, digests)\n }\n\n return ValueDigests.create({ digests: valueDigests })\n }\n\n public async sign(options: {\n signingKey: CoseKey\n algorithm: SignatureAlgorithm\n digestAlgorithm: DigestAlgorithm\n validityInfo: ValidityInfo | ValidityInfoOptions\n deviceKeyInfo: DeviceKeyInfo | DeviceKeyInfoOptions\n certificate: Uint8Array\n }): Promise<IssuerSigned> {\n const validityInfo =\n options.validityInfo instanceof ValidityInfo ? options.validityInfo : ValidityInfo.create(options.validityInfo)\n\n const deviceKeyInfo =\n options.deviceKeyInfo instanceof DeviceKeyInfo\n ? options.deviceKeyInfo\n : DeviceKeyInfo.create(options.deviceKeyInfo)\n\n const mso = MobileSecurityObject.create({\n docType: this.docType,\n validityInfo,\n digestAlgorithm: options.digestAlgorithm,\n deviceKeyInfo,\n valueDigests: await this.convertIssuerNamespacesIntoValueDigests(options.digestAlgorithm),\n })\n\n const protectedHeaders = ProtectedHeaders.create({\n protectedHeaders: new Map([[Header.Algorithm, options.algorithm]]),\n })\n\n const unprotectedHeaders = UnprotectedHeaders.create({\n unprotectedHeaders: new Map([[Header.X5Chain, options.certificate]]),\n })\n\n if (options.signingKey.keyId) {\n unprotectedHeaders.headers?.set(Header.KeyId, options.signingKey.keyId)\n }\n\n const issuerAuth = await IssuerAuth.create(\n {\n payload: mso,\n unprotectedHeaders,\n protectedHeaders,\n signingKey: options.signingKey,\n },\n this.ctx\n )\n\n return IssuerSigned.create({\n issuerNamespaces: this.namespaces,\n issuerAuth,\n })\n }\n}\n","import type { MdocContext } from './context'\nimport type { CoseKey } from './cose'\nimport {\n type DeviceNamespaces,\n DeviceRequest,\n DeviceResponse,\n IssuerSigned,\n SessionTranscript,\n type VerificationCallback,\n} from './mdoc'\nimport { base64url } from './utils'\n\nexport class Holder {\n /**\n *\n * string should be base64url encoded as defined in openid4vci Draft 15\n *\n */\n public static async verifyIssuerSigned(\n options: {\n issuerSigned: Uint8Array | string | IssuerSigned\n verificationCallback?: VerificationCallback\n now?: Date\n disableCertificateChainValidation?: boolean\n trustedCertificates?: Array<Uint8Array>\n skewSeconds?: number\n },\n ctx: Pick<MdocContext, 'cose' | 'x509'>\n ) {\n const issuerSigned =\n typeof options.issuerSigned === 'string'\n ? IssuerSigned.decode(base64url.decode(options.issuerSigned))\n : options.issuerSigned instanceof Uint8Array\n ? IssuerSigned.decode(options.issuerSigned)\n : options.issuerSigned\n\n await issuerSigned.issuerAuth.verify(options, ctx)\n }\n\n public static async verifyDeviceRequest(\n options: {\n deviceRequest: Uint8Array | DeviceRequest\n sessionTranscript: Uint8Array | SessionTranscript\n verificationCallback?: VerificationCallback\n },\n ctx: Pick<MdocContext, 'cose' | 'x509'>\n ) {\n const deviceRequest =\n options.deviceRequest instanceof DeviceRequest\n ? options.deviceRequest\n : DeviceRequest.decode(options.deviceRequest)\n\n const sessionTranscript =\n options.sessionTranscript instanceof SessionTranscript\n ? options.sessionTranscript\n : SessionTranscript.decode(options.sessionTranscript)\n\n for (const docRequest of deviceRequest.docRequests) {\n await docRequest.readerAuth?.verify(\n {\n readerAuthentication: {\n itemsRequest: docRequest.itemsRequest,\n sessionTranscript,\n },\n verificationCallback: options.verificationCallback,\n },\n ctx\n )\n }\n }\n\n public static async createDeviceResponseForDeviceRequest(\n options: {\n deviceRequest: DeviceRequest\n sessionTranscript: SessionTranscript | Uint8Array\n issuerSigned: Array<IssuerSigned>\n deviceNamespaces?: DeviceNamespaces\n mac?: {\n ephemeralKey: CoseKey\n signingKey: CoseKey\n }\n signature?: {\n signingKey: CoseKey\n }\n },\n context: Pick<MdocContext, 'cose' | 'crypto'>\n ) {\n return await DeviceResponse.createWithDeviceRequest(options, context)\n }\n}\n","import type { MdocContext } from './context'\nimport { CoseKey, type DigestAlgorithm, type SignatureAlgorithm } from './cose'\nimport type {\n DeviceKeyInfo,\n DeviceKeyInfoOptions,\n DocType,\n IssuerSigned,\n Namespace,\n ValidityInfo,\n ValidityInfoOptions,\n} from './mdoc'\nimport { IssuerSignedBuilder } from './mdoc/builders'\n\nexport class Issuer {\n private isb: IssuerSignedBuilder\n\n public constructor(docType: DocType, ctx: Pick<MdocContext, 'cose' | 'crypto'>) {\n this.isb = new IssuerSignedBuilder(docType, ctx)\n }\n\n public addIssuerNamespace(namespace: Namespace, value: Record<string | number, unknown>) {\n this.isb = this.isb.addIssuerNamespace(namespace, value)\n return this\n }\n\n public async sign(options: {\n signingKey: CoseKey | Record<string | number, unknown>\n algorithm: SignatureAlgorithm\n digestAlgorithm: DigestAlgorithm\n validityInfo: ValidityInfo | ValidityInfoOptions\n deviceKeyInfo: DeviceKeyInfo | DeviceKeyInfoOptions\n certificate: Uint8Array\n }): Promise<IssuerSigned> {\n const signingKey = options.signingKey instanceof CoseKey ? options.signingKey : CoseKey.fromJwk(options.signingKey)\n return await this.isb.sign({ ...options, signingKey })\n }\n}\n","import type { MdocContext } from './context.js'\nimport type { CoseKey } from './cose/index.js'\nimport type { VerificationCallback } from './mdoc/check-callback.js'\nimport { type DeviceRequest, DeviceResponse, type SessionTranscript } from './mdoc/index.js'\n\nexport class Verifier {\n public static async verifyDeviceResponse(\n options: {\n deviceRequest?: DeviceRequest\n deviceResponse: Uint8Array | DeviceResponse\n sessionTranscript: SessionTranscript | Uint8Array\n ephemeralReaderKey?: CoseKey\n disableCertificateChainValidation?: boolean\n trustedCertificates: Uint8Array[]\n now?: Date\n onCheck?: VerificationCallback\n skewSeconds?: number\n },\n ctx: Pick<MdocContext, 'cose' | 'x509' | 'crypto'>\n ) {\n const deviceResponse =\n options.deviceResponse instanceof DeviceResponse\n ? options.deviceResponse\n : DeviceResponse.decode(options.deviceResponse)\n\n await deviceResponse.verify(options, ctx)\n }\n}\n"],"mappings":";;;;;AAGAA,IAAE,OAAO,EACP,aAAa,gBAAgB,EAC9B,CAAC;AAEF,SAAgB,eAAe,OAA4B;AACzD,KAAI,CAAC,MAAO,QAAO;AAEnB,QAAO,UAAU,OAAO;EACtB,QAAQ;EACR,iBAAiB;EACjB,gBAAgB;EAChB,gBAAgB;EACjB,CAAC,CAAC,UAAU;;;;;ACZf,IAAa,kBAAb,cAAqC,MAAM;CAGzC,YAAY,SAAiB,UAAqB;AAChD,QAAM,QAAQ;AAGd,OAAK,UAAU,GAAG,QAAQ,IADH,WAAW,eAAe,SAAS,GAAG;AAG7D,SAAO,eAAe,MAAM,YAAY;GACtC,OAAO;GACP,UAAU;GACV,YAAY;GACb,CAAC;;;;;;ACZN,MAAa,cAAcC,IAAE,WAA+C,WAAW;AAKvF,SAAgB,gCACd,eACA,QACA,MACA,oBACiB;CACjB,MAAM,cAAcA,IAAE,UAAU,QAAQ,KAAK;AAE7C,KAAI,CAAC,YAAY,QACf,OAAM,IAAI,gBAAgB,sBAAsB,kBAAkB,iBAAiB,YAAY,MAAM;AAGvG,QAAO,YAAY;;AAGrB,SAAgB,iCACd,eACA,QACA,MACA,oBACiB;CACjB,MAAM,eAAeA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