{"version":3,"file":"index.mjs","names":["z","z","z","z","z","z","CoseKey","z","z","z","z","z","CoseKey","cborEncode","cborEncode","z","z","Mac0","Sign1","z","CoseKey","z","z","z","z","z","Sign1","z","z","z","z","z","RegisteredCwtClaimKey","cborDecode","ProtectedHeaders","RegisteredCwtHeaderClaimKey","z","z","StatusListInfo","z","z","z","Sign1","cborDecode","RegisteredCwtHeaderClaimKey","SignatureAlgorithm","z","z","z","z","UnprotectedHeaders","RegisteredCwtHeaderClaimKey","ProtectedHeaders","ProtectedHeaders","RegisteredCwtHeaderClaimKey","UnprotectedHeaders","ProtectedHeaders","RegisteredCwtHeaderClaimKey","UnprotectedHeaders","CoseKey"],"sources":["../src/mdoc/models/ble-options.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/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/iso-mdoc-dc-api-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/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/identifier-list.ts","../src/mdoc/models/identifier-list-cwt-payload.ts","../src/mdoc/models/identifier-list-cwt.ts","../src/mdoc/models/identifier-list-info.ts","../src/mdoc/models/status.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 { CborStructure, typedMap, zUint8Array } from '@owf/cose'\nimport { z } from '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","// 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 EitherSignatureOrMacMustBeProvidedError extends MdlError {}\nexport class AtLeastOneCertificateRequiredError extends MdlError {}\nexport class SignatureAlgorithmDoesNotMatchSigningKeyAlgorithmError extends MdlError {}\nexport class UnableToExtractX5ChainFromCwtError extends MdlError {}\nexport class NoPublicKeySetOnStatusListError extends MdlError {}\nexport class InvalidAlgorithmError extends MdlError {}\nexport class InvalidMessageAuthenticationCode extends MdlError {}\nexport class InvalidSignatureError extends MdlError {}\nexport class JwtNotSupportForStatusListError extends MdlError {}\nexport class TrustedRevocationCertificatesMustContainAtleastOneCertificateError extends MdlError {}\nexport class UnableToExtractX5ChainFromIdentifierListError extends MdlError {}\nexport class InvalidIdentifierListSignatureError extends MdlError {}\nexport class IdentifierFoundInRevokedListError 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 { CborStructure } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure, typedMap } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure, typedMap, zUint8Array } from '@owf/cose'\nimport { z } from '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 { CborStructure } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure } from '@owf/cose'\nimport z from 'zod'\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 { CoseKey, type CoseKeyDecodedStructure, type CoseKeyEncodedStructure, type CoseKeyOptions } from '@owf/cose'\n\nexport type EDeviceKeyDecodedStructure = CoseKeyDecodedStructure\nexport type EDeviceKeyEncodedStructure = CoseKeyEncodedStructure\nexport type EDeviceKeyOptions = CoseKeyOptions\n\nexport class EDeviceKey extends CoseKey {}\n","import { CborStructure, DataItem } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\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 { CoseKey, type CoseKeyDecodedStructure, type CoseKeyEncodedStructure, type CoseKeyOptions } from '@owf/cose'\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 '@owf/cose'\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 { cborEncode, zUint8Array } from '@owf/cose'\nimport z from 'zod'\nimport type { MdocContext } from '../../context'\nimport { Handover } from './handover'\n\nconst isoMdocDcApiHandoverEncodedSchema = z.tuple([z.literal('dcapi'), zUint8Array])\nconst isoMdocDcApiHandoverDecodedSchema = zUint8Array\n\nexport type IsoMdocDcApiHandoverEncodedStructure = z.infer<typeof isoMdocDcApiHandoverEncodedSchema>\nexport type IsoMdocDcApiHandoverDecodedStructure = z.infer<typeof isoMdocDcApiHandoverDecodedSchema>\n\nexport type IsoMdocDcApiHandoverOptions = {\n  encryptionInfoBase64Url: string\n  origin: string\n}\n\n/**\n * Handover for the ISO 18013-7 Annex C `org-iso-mdoc` DC API protocol.\n *\n *   DCAPIHandover = [ \"dcapi\", SHA-256(CBOR([encInfoB64u, origin])) ]\n */\nexport class IsoMdocDcApiHandover extends Handover<\n  IsoMdocDcApiHandoverEncodedStructure,\n  IsoMdocDcApiHandoverDecodedStructure\n> {\n  public static override get encodingSchema() {\n    return z.codec(isoMdocDcApiHandoverEncodedSchema, isoMdocDcApiHandoverDecodedSchema, {\n      encode: (handoverInfoHash) => ['dcapi', handoverInfoHash] satisfies IsoMdocDcApiHandoverEncodedStructure,\n      decode: ([, handoverInfoHash]) => handoverInfoHash,\n    })\n  }\n\n  public static createFromHash(dcApiInfoHash: Uint8Array) {\n    return this.fromDecodedStructure(dcApiInfoHash)\n  }\n\n  public static async create(options: IsoMdocDcApiHandoverOptions, ctx: Pick<MdocContext, 'crypto'>) {\n    const dcapiInfoBytes = cborEncode([options.encryptionInfoBase64Url, options.origin])\n    const dcApiInfoHash = await ctx.crypto.digest({\n      digestAlgorithm: 'SHA-256',\n      bytes: dcapiInfoBytes,\n    })\n    return this.fromDecodedStructure(dcApiInfoHash)\n  }\n}\n","import { zUint8Array } from '@owf/cose'\nimport z from '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 { CborStructure } from '@owf/cose'\nimport z from 'zod'\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 { zUint8Array } from '@owf/cose'\nimport z from 'zod'\nimport type { MdocContext } from '../../context'\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 { CborStructure, zUint8Array } from '@owf/cose'\nimport z from '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 { cborEncode, zUint8Array } from '@owf/cose'\nimport z from 'zod'\nimport type { MdocContext } from '../../context'\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 { zUint8Array } from '@owf/cose'\nimport z from 'zod'\nimport type { MdocContext } from '../../context'\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 { CborStructure, zUint8Array } from '@owf/cose'\nimport z from '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 { zUint8Array } from '@owf/cose'\nimport z from 'zod'\nimport type { MdocContext } from '../../context'\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 { CborStructure, zUint8Array } from '@owf/cose'\nimport z from '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 { CborStructure, DataItem } from '@owf/cose'\nimport { z } from 'zod'\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 { IsoMdocDcApiHandover, type IsoMdocDcApiHandoverOptions } from './iso-mdoc-dc-api-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  IsoMdocDcApiHandover,\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  /**\n   * Create a SessionTranscript for the ISO 18013-7 Annex C\n   * `org-iso-mdoc` DC API protocol.\n   */\n  public static async forIsoMdocDcApi(options: IsoMdocDcApiHandoverOptions, ctx: Pick<MdocContext, 'crypto'>) {\n    const handover = await IsoMdocDcApiHandover.create(options, ctx)\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 { CborStructure, DataItem } from '@owf/cose'\nimport { z } from 'zod'\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 { CoseKey, Mac0Options } from '@owf/cose'\nimport { Mac0, type Mac0DecodedStructure, type Mac0EncodedStructure } from '@owf/cose'\nimport { stringToBytes } from '@owf/identity-common'\nimport type { MdocContext } from '../../context'\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      detachedPayload?: Uint8Array\n    },\n    ctx: Pick<MdocContext, 'crypto' | 'cose'>\n  ) {\n    const key = await this.createDeviceMacKey(options, ctx)\n\n    return ctx.cose.mac0.verify({\n      toBeAuthenticated: this.toBeAuthenticated({\n        detachedPayload: options.detachedPayload,\n      }),\n      key,\n      tag: this.tag,\n    })\n  }\n\n  public static create(options: DeviceMacOptions) {\n    return super.create(options) as DeviceMac\n  }\n\n  public async createDeviceMacKey(\n    options: {\n      publicKey: CoseKey\n      privateKey: CoseKey\n      sessionTranscript: SessionTranscript | Uint8Array\n      info?: 'EMacKey' | 'SKReader' | 'SKDevice'\n    },\n    ctx: Pick<MdocContext, 'crypto' | 'cose'>\n  ) {\n    return await ctx.crypto.hdkf({\n      privateKey: options.privateKey.privateKey,\n      publicKey: options.publicKey.publicKey,\n      salt: await ctx.crypto.digest({\n        digestAlgorithm: 'SHA-256',\n        bytes:\n          options.sessionTranscript instanceof SessionTranscript\n            ? options.sessionTranscript.encode({ asDataItem: true })\n            : options.sessionTranscript,\n      }),\n      info: stringToBytes(options.info ?? 'EMacKey'),\n    })\n  }\n}\n","import { Sign1, type Sign1DecodedStructure, type Sign1EncodedStructure, type Sign1Options } from '@owf/cose'\n\nexport type DeviceSignatureEncodedStructure = Sign1EncodedStructure\nexport type DeviceSignatureDecodedStructure = Sign1DecodedStructure\nexport type DeviceSignatureOptions = Sign1Options\n\nexport class DeviceSignature extends Sign1 {}\n","import { CborStructure, type CoseKey, MacAlgorithm, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport type { MdocContext } from '../../context'\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        const verificationResult = await ctx.cose.sign1.verify({\n          toBeVerified: deviceSignature.toBeSigned({ detachedPayload: deviceAuthenticationBytes }),\n          key: deviceKey,\n          signature: deviceSignature.signature,\n        })\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.algorithm !== 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        const isValid = await deviceMac.verify(\n          {\n            publicKey: deviceKey,\n            privateKey: options.ephemeralMacPrivateKey,\n            sessionTranscript: options.sessionTranscript,\n            info: 'EMacKey',\n            detachedPayload: deviceAuthenticationBytes,\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 { CoseKey, type CoseKeyDecodedStructure, type CoseKeyEncodedStructure, type CoseKeyOptions } from '@owf/cose'\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 { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure, typedMap } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure, DataItem } from '@owf/cose'\nimport { z } from 'zod'\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 { Sign1, type Sign1DecodedStructure, type Sign1EncodedStructure, type Sign1Options } from '@owf/cose'\nimport type { MdocContext } from '../../context'\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       * Trust anchors for the reader's certificate chain (e.g. CAs listed in a\n       * RICAL). When provided, the chain in this Sign1's x5chain header is\n       * validated against these anchors per RFC 5280. When omitted, only the\n       * detached signature is verified — chain trust is not established.\n       */\n      trustedCertificates?: Array<Uint8Array>\n      now?: Date\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    const isValid = await this.verifySignature(\n      {\n        key: await ctx.x509.getPublicKey({ certificate: this.certificate, algorithm: this.algorithm }),\n        detachedPayload: readerAuthentication.encode({ asDataItem: true }),\n      },\n      { verify: ctx.cose.sign1.verify }\n    )\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    if (options.trustedCertificates) {\n      try {\n        if (options.trustedCertificates.length === 0) {\n          throw new Error('No trusted reader certificates provided.')\n        }\n\n        await ctx.x509.verifyCertificateChain({\n          trustedCertificates: options.trustedCertificates,\n          x5chain: this.certificateChain,\n          now: options.now ?? new Date(),\n        })\n\n        onCheck({\n          status: 'PASSED',\n          check: 'Reader certificate chain must be trusted',\n        })\n      } catch (err) {\n        onCheck({\n          status: 'FAILED',\n          check: 'Reader certificate chain must be trusted',\n          reason: err instanceof Error ? err.message : 'Unknown error',\n        })\n      }\n    }\n  }\n\n  public static create(options: ReaderAuthOptions) {\n    return super.create(options) as ReaderAuth\n  }\n}\n","import { CborStructure, DataItem, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\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?.[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 { CborStructure, typedMap, zUint8Array } from '@owf/cose'\nimport { compareBytes } from '@owf/identity-common'\nimport { z } from 'zod'\nimport type { MdocContext } from '../../context'\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 { CborStructure, DataItem } from '@owf/cose'\nimport z from 'zod'\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 { CborStructure, DataItem, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure, TypedMap, typedMap, zUint8Array } from '@owf/cose'\nimport { compareBytes } from '@owf/identity-common'\nimport { z } from 'zod'\n\n/**\n * IdentifierList payload structure carried inside an `IdentifierListCwt`.\n * ISO/IEC 18013-5 second edition § 12.3.6.4:\n *\n *   IdentifierList = {\n *     \"identifiers\"      : { * Identifier => IdentifierInfo },\n *     ? \"aggregation_uri\": Aggregation_uri,\n *     * tstr             => RFU\n *   }\n *\n *   IdentifierInfo = { tstr/int => RFU }   ; empty-allowed RFU map\n *   Identifier     = bstr\n *\n * Presence of an `Identifier` in `identifiers` means the MSO carrying that\n * id in its `identifier_list` element is revoked; absence means valid.\n */\nconst identifierInfoSchema = z.map(z.union([z.string(), z.number()]), z.unknown())\n\nconst identifierListSchema = typedMap(\n  [\n    ['identifiers', z.map(zUint8Array, identifierInfoSchema)],\n    ['aggregation_uri', z.string().exactOptional()],\n  ],\n  { allowAdditionalKeys: true }\n)\n\nexport type IdentifierListDecodedStructure = z.output<typeof identifierListSchema>\nexport type IdentifierListEncodedStructure = z.input<typeof identifierListSchema>\n\nexport type IdentifierListOptions = {\n  identifiers: Array<Uint8Array>\n  aggregationUri?: string\n}\n\nexport class IdentifierList extends CborStructure<IdentifierListEncodedStructure, IdentifierListDecodedStructure> {\n  public static override get encodingSchema() {\n    return identifierListSchema\n  }\n\n  public get identifiers() {\n    return this.structure.get('identifiers')\n  }\n\n  public get aggregationUri() {\n    return this.structure.get('aggregation_uri')\n  }\n\n  public includes(id: Uint8Array): boolean {\n    const ids = this.identifiers\n    if (!ids) return false\n    for (const entry of ids.keys()) {\n      if (compareBytes(entry, id)) return true\n    }\n    return false\n  }\n\n  public static create(options: IdentifierListOptions): IdentifierList {\n    const ids = new Map<Uint8Array, Map<string | number, unknown>>()\n    for (const id of options.identifiers) ids.set(id, new Map())\n    const map: IdentifierListDecodedStructure = new TypedMap([['identifiers', ids]])\n    if (options.aggregationUri !== undefined) {\n      map.set('aggregation_uri', options.aggregationUri)\n    }\n    return this.fromDecodedStructure(map)\n  }\n}\n","import { CborStructure, RegisteredCwtClaimKey, TypedMap, typedMap } from '@owf/cose'\nimport z from 'zod'\nimport { IdentifierList, type IdentifierListEncodedStructure } from './identifier-list'\n\n/**\n * CWT payload claim carrying the identifier list (ISO/IEC 18013-5 second\n * edition § 12.3.6). Mirrors `StatusListCwtPayload` from\n * `@owf/token-status-list`.\n */\nexport enum IdentifierListCwtClaimKey {\n  IdentifierList = 65530,\n}\n\n/**\n * Generic CWT registered claim keys not yet exposed by `@owf/cose`'s\n * `RegisteredCwtClaimKey`. Inline pending an upstream addition.\n */\nexport enum CwtClaimKey {\n  /** `typ` claim, RFC 9596 § 4.1. */\n  Typ = 16,\n}\n\n/** CWT content type strings used by ISO 18013-5 revocation lists. */\nexport enum MediaTypes {\n  IdentifierListCwt = 'application/identifierlist+cwt',\n}\n\nconst identifierListCwtPayloadSchema = typedMap(\n  [\n    [RegisteredCwtClaimKey.Subject, z.string().exactOptional()],\n    [RegisteredCwtClaimKey.IssuedAt, z.number().exactOptional()],\n    // ISO 18013-5 § 12.3.6.3: \"The exp claim shall be present.\"\n    [RegisteredCwtClaimKey.ExpirationTime, z.number()],\n    // § 12.3.6.4: \"The value of the type claim shall be\n    // 'application/identifierlist+cwt'\".\n    [CwtClaimKey.Typ, z.literal(MediaTypes.IdentifierListCwt)],\n    [IdentifierListCwtClaimKey.IdentifierList, z.instanceof(IdentifierList)],\n  ],\n  { allowAdditionalKeys: true }\n)\n\nexport type IdentifierListCwtPayloadEncodedStructure = z.infer<typeof identifierListCwtPayloadSchema>\nexport type IdentifierListCwtPayloadDecodedStructure = z.infer<typeof identifierListCwtPayloadSchema>\n\nexport type CreateIdentifierListCwtPayloadOptions = {\n  identifierList: IdentifierList\n  subject?: string\n  issuedAt?: Date\n  expirationTime?: Date\n}\n\nexport class IdentifierListCwtPayload extends CborStructure<\n  IdentifierListCwtPayloadEncodedStructure,\n  IdentifierListCwtPayloadDecodedStructure\n> {\n  public static override get encodingSchema() {\n    return z.codec(identifierListCwtPayloadSchema.in, identifierListCwtPayloadSchema.out, {\n      decode: (input) => {\n        const map: IdentifierListCwtPayloadDecodedStructure = TypedMap.fromMap(input)\n        map.set(\n          IdentifierListCwtClaimKey.IdentifierList,\n          IdentifierList.fromEncodedStructure(\n            input.get(IdentifierListCwtClaimKey.IdentifierList) as IdentifierListEncodedStructure\n          )\n        )\n        return map\n      },\n      encode: (output) => {\n        const map = output.toMap() as Map<unknown, unknown>\n        map.set(\n          IdentifierListCwtClaimKey.IdentifierList,\n          output.get(IdentifierListCwtClaimKey.IdentifierList).encodedStructure\n        )\n        return map\n      },\n    })\n  }\n\n  public static create(options: CreateIdentifierListCwtPayloadOptions) {\n    if (!options.expirationTime) {\n      // ISO 18013-5 § 12.3.6.3: exp claim shall be present.\n      throw new Error('IdentifierListCwtPayload.create: expirationTime is required')\n    }\n    const map: IdentifierListCwtPayloadDecodedStructure = new TypedMap([\n      [RegisteredCwtClaimKey.ExpirationTime, Math.floor(options.expirationTime.getTime() / 1000)],\n      [CwtClaimKey.Typ, MediaTypes.IdentifierListCwt],\n      [IdentifierListCwtClaimKey.IdentifierList, options.identifierList],\n    ])\n    if (options.subject !== undefined) {\n      map.set(RegisteredCwtClaimKey.Subject, options.subject)\n    }\n    map.set(RegisteredCwtClaimKey.IssuedAt, Math.floor((options.issuedAt ?? new Date()).getTime() / 1000))\n    return new IdentifierListCwtPayload(identifierListCwtPayloadSchema.parse(map.toMap()))\n  }\n\n  public get identifierList() {\n    return this.structure.get(IdentifierListCwtClaimKey.IdentifierList)\n  }\n\n  public get subject() {\n    return this.structure.get(RegisteredCwtClaimKey.Subject)\n  }\n\n  public get issuedAt() {\n    const v = this.structure.get(RegisteredCwtClaimKey.IssuedAt)\n    return v !== undefined ? new Date(v * 1000) : undefined\n  }\n\n  public get expirationTime() {\n    const v = this.structure.get(RegisteredCwtClaimKey.ExpirationTime)\n    return v !== undefined ? new Date(v * 1000) : undefined\n  }\n}\n","import {\n  type CoseKey,\n  Cwt,\n  cborDecode,\n  ProtectedHeaders,\n  RegisteredCwtHeaderClaimKey,\n  type Sign1Context,\n  type SignatureAlgorithm,\n} from '@owf/cose'\nimport { StatusListCwtClaimKey } from '@owf/token-status-list'\nimport type { MdocContext } from '../../context'\nimport {\n  IdentifierListCwtClaimKey,\n  IdentifierListCwtPayload,\n  type IdentifierListCwtPayloadEncodedStructure,\n} from './identifier-list-cwt-payload'\n\n/**\n * Signed CWT carrying the list of revoked MSO identifiers (ISO/IEC 18013-5\n * second edition § 12.3.6). The payload is decoded as\n * `IdentifierListCwtPayload`; signature verification mirrors `StatusListCwt`.\n */\nexport class IdentifierListCwt {\n  private constructor(\n    private readonly cwt: Cwt,\n    public readonly payload: IdentifierListCwtPayload\n  ) {}\n\n  public static fromBytes(bytes: Uint8Array): IdentifierListCwt {\n    const cwt = Cwt.fromToken(bytes)\n    if (!cwt.payload) {\n      throw new Error('IdentifierList CWT has no payload')\n    }\n    const decoded = cborDecode(cwt.payload, { unwrapTopLevelDataItem: false }) as Map<unknown, unknown>\n    // § 12.3.6.4: \"The StatusList claim shall not be present in the CWT\n    // claims set\" for an identifier-list CWT. The `typ` claim's presence\n    // and value are enforced by `IdentifierListCwtPayload`'s schema.\n    if (decoded.has(StatusListCwtClaimKey.StatusList)) {\n      throw new Error('IdentifierList CWT must not contain a StatusList claim (ISO 18013-5 § 12.3.6.4)')\n    }\n    const payload = IdentifierListCwtPayload.fromEncodedStructure(\n      decoded as unknown as IdentifierListCwtPayloadEncodedStructure\n    )\n    return new IdentifierListCwt(cwt, payload)\n  }\n\n  public static async fetch(uri: string, ctx: Pick<MdocContext, 'fetch'>): Promise<IdentifierListCwt> {\n    const fetcher = ctx.fetch ?? fetch\n    const response = await fetcher(uri, {\n      headers: { Accept: 'application/identifierlist+cwt' },\n    })\n    if (!response.ok) {\n      throw new Error(`Identifier list fetch failed: ${response.status}`)\n    }\n    return IdentifierListCwt.fromBytes(new Uint8Array(await response.arrayBuffer()))\n  }\n\n  public get protectedHeaders(): ProtectedHeaders | undefined {\n    const h = this.cwt.protectedHeaders\n    return h instanceof ProtectedHeaders ? h : undefined\n  }\n\n  /** Leaf cert + chain from the CWT's protected x5chain header, normalized to an array. */\n  public get x5chain(): Array<Uint8Array> | undefined {\n    const x5c = this.protectedHeaders?.headers?.get(RegisteredCwtHeaderClaimKey.X5Chain) as\n      | Uint8Array\n      | Uint8Array[]\n      | undefined\n    if (x5c instanceof Uint8Array) return [x5c]\n    if (Array.isArray(x5c) && x5c.every((e) => e instanceof Uint8Array)) return x5c\n    return undefined\n  }\n\n  public get algorithm(): SignatureAlgorithm | undefined {\n    return this.protectedHeaders?.headers?.get(RegisteredCwtHeaderClaimKey.Algorithm) as SignatureAlgorithm | undefined\n  }\n\n  /** Verify the COSE_Sign1 signature against the provided public key. */\n  public async verifySignature(options: { key: CoseKey }, ctx: Pick<Sign1Context, 'verify'>): Promise<boolean> {\n    return this.cwt.asSign1.verifySignature(options, ctx)\n  }\n\n  /** True when `id` appears in the published list (and the credential is therefore revoked). */\n  public includes(id: Uint8Array): boolean {\n    return this.payload.identifierList.includes(id)\n  }\n}\n\nexport { IdentifierListCwtClaimKey }\n","import { CborStructure, TypedMap, typedMap, zUint8Array } from '@owf/cose'\nimport { z } from 'zod'\n\n/**\n * IdentifierListInfo carries an opaque per-MSO identifier and the location of\n * the published list of revoked identifiers.\n *\n * Defined in ISO/IEC 18013-5 second edition (CD), 12.3.6.\n *\n * The `id` is an opaque byte string the issuer assigns to this MSO (recommended\n * unique and random per credential). Revocation is signalled by publishing the\n * id in the identifier list at `uri`. Absence from the list means the credential\n * is valid.\n */\nconst identifierListInfoSchema = typedMap([\n  ['id', zUint8Array],\n  ['uri', z.string()],\n  ['certificate', zUint8Array.exactOptional()],\n])\n\nexport type IdentifierListInfoDecodedStructure = z.output<typeof identifierListInfoSchema>\nexport type IdentifierListInfoEncodedStructure = z.input<typeof identifierListInfoSchema>\n\nexport type IdentifierListInfoOptions = {\n  id: Uint8Array\n  uri: string\n  certificate?: Uint8Array\n}\n\nexport class IdentifierListInfo extends CborStructure<\n  IdentifierListInfoEncodedStructure,\n  IdentifierListInfoDecodedStructure\n> {\n  public static override get encodingSchema() {\n    return identifierListInfoSchema\n  }\n\n  public get id() {\n    return this.structure.get('id')\n  }\n\n  public get uri() {\n    return this.structure.get('uri')\n  }\n\n  public get certificate() {\n    return this.structure.get('certificate')\n  }\n\n  public static create(options: IdentifierListInfoOptions): IdentifierListInfo {\n    const map: IdentifierListInfoDecodedStructure = new TypedMap([\n      ['id', options.id],\n      ['uri', options.uri],\n    ])\n    if (options.certificate) {\n      map.set('certificate', options.certificate)\n    }\n    return this.fromDecodedStructure(map)\n  }\n}\n","import { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { StatusListInfo, type StatusListInfoEncodedStructure, type StatusListInfoOptions } from '@owf/token-status-list'\nimport { z } from 'zod'\nimport {\n  IdentifierListInfo,\n  type IdentifierListInfoEncodedStructure,\n  type IdentifierListInfoOptions,\n} from './identifier-list-info'\n\n/**\n * Status references one or both of the revocation mechanisms defined in\n * ISO/IEC 18013-5 second edition (CD), 12.3.6:\n *\n *   Status = {\n *     ? \"status_list\": StatusListInfo,       ; IETF Token Status List entry\n *     ? \"identifier_list\": IdentifierListInfo,\n *     * tstr => RFU,\n *   }\n *\n * Either or both members may be present. The mDL profile uses only the\n * VALID / INVALID states (no temporary suspension).\n *\n * Status is embedded inside the MobileSecurityObject as an optional member\n * so issuers can publish revocation status for issued credentials, and\n * verifiers can check it during presentation.\n */\nconst statusSchema = typedMap([\n  ['status_list', z.instanceof(StatusListInfo).exactOptional()],\n  ['identifier_list', z.instanceof(IdentifierListInfo).exactOptional()],\n])\n\nexport type StatusDecodedStructure = z.output<typeof statusSchema>\nexport type StatusEncodedStructure = z.input<typeof statusSchema>\n\nexport type StatusOptions = {\n  statusList?: StatusListInfo | StatusListInfoOptions\n  identifierList?: IdentifierListInfo | IdentifierListInfoOptions\n}\n\nexport class Status extends CborStructure<StatusEncodedStructure, StatusDecodedStructure> {\n  public static override get encodingSchema() {\n    return z.codec(statusSchema.in, statusSchema.out, {\n      decode: (input) => {\n        const map: StatusDecodedStructure = TypedMap.fromMap(input)\n\n        if (input.has('status_list')) {\n          map.set(\n            'status_list',\n            StatusListInfo.fromEncodedStructure(input.get('status_list') as StatusListInfoEncodedStructure)\n          )\n        }\n        if (input.has('identifier_list')) {\n          map.set(\n            'identifier_list',\n            IdentifierListInfo.fromEncodedStructure(input.get('identifier_list') as IdentifierListInfoEncodedStructure)\n          )\n        }\n        return map\n      },\n      encode: (output) => {\n        const map = output.toMap() as Map<unknown, unknown>\n        const statusList = output.get('status_list')\n        if (statusList) {\n          map.set('status_list', statusList.encodedStructure)\n        }\n        const identifierList = output.get('identifier_list')\n        if (identifierList) {\n          map.set('identifier_list', identifierList.encodedStructure)\n        }\n        return map\n      },\n    })\n  }\n\n  public get statusList() {\n    return this.structure.get('status_list')\n  }\n\n  public get identifierList() {\n    return this.structure.get('identifier_list')\n  }\n\n  public static create(options: StatusOptions): Status {\n    const map: StatusDecodedStructure = new TypedMap()\n    if (options.statusList) {\n      map.set(\n        'status_list',\n        options.statusList instanceof StatusListInfo ? options.statusList : StatusListInfo.create(options.statusList)\n      )\n    }\n    if (options.identifierList) {\n      map.set(\n        'identifier_list',\n        options.identifierList instanceof IdentifierListInfo\n          ? options.identifierList\n          : IdentifierListInfo.create(options.identifierList)\n      )\n    }\n    return this.fromDecodedStructure(map)\n  }\n}\n","import { CborStructure, typedMap } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure, zUint8Array } from '@owf/cose'\nimport { z } from '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 type { DigestAlgorithm } from '@owf/cose'\nimport { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { DeviceKeyInfo, type DeviceKeyInfoEncodedStructure } from './device-key-info'\nimport type { DocType } from './doctype'\nimport { Status, type StatusEncodedStructure } from './status'\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  // Optional Status, defined in ISO/IEC 18013-5 second edition (CD), 12.3.6.\n  // Carries Status List and/or Identifier List references for revocation.\n  ['status', z.instanceof(Status).exactOptional()],\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  status?: Status\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        if (input.has('status')) {\n          map.set('status', Status.fromEncodedStructure(input.get('status') as StatusEncodedStructure))\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        const status = output.get('status')\n        if (status) {\n          map.set('status', status.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 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 get status() {\n    return this.structure.get('status')\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    if (options.status) {\n      map.set('status', options.status)\n    }\n\n    return this.fromDecodedStructure(map)\n  }\n}\n","import {\n  CosePayloadMustBeDefinedError,\n  cborDecode,\n  DataItem,\n  MacAlgorithm,\n  RegisteredCwtHeaderClaimKey,\n  Sign1,\n  type Sign1EncodedStructure,\n  type Sign1Options,\n  SignatureAlgorithm,\n  zUint8Array,\n} from '@owf/cose'\nimport { compareBytes } from '@owf/identity-common'\nimport { fetchStatusList, StatusListCwt } from '@owf/token-status-list'\nimport z from 'zod'\nimport type { MdocContext } from '../../context.js'\nimport { defaultVerificationCallback, onCategoryCheck, type VerificationCallback } from '../check-callback.js'\nimport {\n  IdentifierFoundInRevokedListError,\n  InvalidAlgorithmError,\n  InvalidIdentifierListSignatureError,\n  InvalidMessageAuthenticationCode,\n  InvalidSignatureError,\n  JwtNotSupportForStatusListError,\n  NoPublicKeySetOnStatusListError,\n  TrustedRevocationCertificatesMustContainAtleastOneCertificateError,\n  UnableToExtractX5ChainFromCwtError,\n  UnableToExtractX5ChainFromIdentifierListError,\n} from '../errors.js'\nimport { IdentifierListCwt } from './identifier-list-cwt'\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 type IssuerAuthVerificationResult = {\n  trustedIssuanceChain: Uint8Array[]\n  statusList?: StatusListCwt\n  trustedStatusListChain?: Uint8Array[]\n  identifierList?: IdentifierListCwt\n  trustedIdentifierListChain?: Uint8Array[]\n}\n\nexport class IssuerAuth extends Sign1 {\n  public static create(options: IssuerAuthOptions): IssuerAuth {\n    return super.create({\n      ...options,\n      payload:\n        options.payload instanceof MobileSecurityObject\n          ? options.payload.encode({ asDataItem: true })\n          : (options.payload ?? null),\n    }) as 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 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  /**\n   * Verifies the MSO's revocation status. Throws on revocation or\n   * a CWT-signature failure; succeeds silently otherwise.\n   *\n   * @todo return the full verified chain for audit / compliance.\n   */\n  public async verifyStatus(\n    {\n      now = new Date(),\n      checkFreshness,\n      trustedStatusCertificates,\n    }: {\n      now?: Date\n      checkFreshness?: boolean\n      trustedStatusCertificates?: Uint8Array[]\n    },\n    ctx: Pick<MdocContext, 'fetch' | 'x509' | 'cose'>\n  ): Promise<{\n    statusList?: StatusListCwt\n    trustedStatusListChain?: Uint8Array[]\n    identifierList?: IdentifierListCwt\n    trustedIdentifierListChain?: Uint8Array[]\n  }> {\n    const status = this.mobileSecurityObject.status\n    if (!status || (!status.statusList && !status.identifierList)) return {}\n\n    if (!trustedStatusCertificates || trustedStatusCertificates.length <= 0) {\n      throw new TrustedRevocationCertificatesMustContainAtleastOneCertificateError(\n        'Atleast one certificate is required to check the status of the mdoc. Make sure to supply them in the `trustedStatusCertificates` option'\n      )\n    }\n\n    let statusList: StatusListCwt | undefined\n    let trustedStatusListChain: Uint8Array[] | undefined\n\n    if (status.statusList) {\n      const { uri, idx } = status.statusList\n      const statusListToken = await fetchStatusList({ uri, customFetcher: ctx.fetch, acceptedFormats: ['cwt'] })\n\n      if (typeof statusListToken === 'string') {\n        throw new JwtNotSupportForStatusListError(\n          'Could not verify status list token. @owf/mdoc currently does not support JWT format for status list, only CWT'\n        )\n      }\n\n      const cwt = StatusListCwt.fromToken(statusListToken)\n\n      // TODO: we should add this utility section to the cwt/sign1/mac0 class\n      // TODO: support multiple ways to set the public key\n      const x5c = cwt.protectedHeaders?.headers.get(RegisteredCwtHeaderClaimKey.X5Chain) as\n        | Uint8Array\n        | Uint8Array[]\n        | undefined\n\n      if (!x5c) {\n        throw new UnableToExtractX5ChainFromCwtError()\n      }\n\n      const algorithm = cwt.protectedHeaders?.headers.get(RegisteredCwtHeaderClaimKey.Algorithm) as SignatureAlgorithm\n      const x5chain =\n        x5c instanceof Uint8Array\n          ? [x5c]\n          : Array.isArray(x5c) && x5c.every((e) => e instanceof Uint8Array)\n            ? x5c\n            : undefined\n\n      if (!x5chain) {\n        throw new UnableToExtractX5ChainFromCwtError()\n      }\n\n      const [certificate] = x5chain\n\n      const { chain: statusChain } = await ctx.x509.verifyCertificateChain({\n        trustedCertificates: trustedStatusCertificates,\n        x5chain,\n      })\n\n      const publicKey = await ctx.x509.getPublicKey({ certificate, algorithm })\n      const alg = algorithm ?? publicKey.algorithm\n\n      if (!publicKey) {\n        throw new NoPublicKeySetOnStatusListError()\n      }\n\n      if (Object.values(SignatureAlgorithm).includes(alg as SignatureAlgorithm)) {\n        if (!(await cwt.verifySignature({ key: publicKey }, ctx.cose.sign1))) {\n          throw new InvalidSignatureError('Incorrect signature for CWT statuslist')\n        }\n      } else if (Object.values(MacAlgorithm).includes(alg as unknown as MacAlgorithm)) {\n        if (!(await cwt.verifyAuthenticationCode({ key: publicKey }, ctx.cose.mac0))) {\n          throw new InvalidMessageAuthenticationCode('Incorrect message authentication code for CWT status list')\n        }\n      } else {\n        throw new InvalidAlgorithmError(\n          `Invalid algorithm (claim ${RegisteredCwtHeaderClaimKey.Algorithm}) set. Value '${alg}', therefore unable to verify the CWT token status list`\n        )\n      }\n\n      cwt.verifyStatus({ uri, idx, now, checkFreshness })\n      statusList = cwt\n      trustedStatusListChain = statusChain\n    }\n\n    let identifierList: IdentifierListCwt | undefined\n    let trustedIdentifierListChain: Uint8Array[] | undefined\n\n    if (status.identifierList) {\n      // ISO/IEC 18013-5 second edition § 12.3.6.4 (identifier list).\n      // The MSO's `IdentifierListInfo` carries the URI of an\n      // `IdentifierListCwt` and the per-MSO `id` (bstr). The list\n      // enumerates revoked identifiers; presence == revoked.\n      const { uri, id } = status.identifierList\n      const cwt = await IdentifierListCwt.fetch(uri, ctx)\n\n      const x5chain = cwt.x5chain\n      if (!x5chain || x5chain.length === 0) {\n        throw new UnableToExtractX5ChainFromIdentifierListError()\n      }\n\n      // Identifier-list CWTs MUST carry an x5chain in the protected\n      // header (§ 12.3.6.3); the chain anchors back to a trusted\n      // status-cert root so the caller can vet the issuer.\n      const { chain: identifierChain } = await ctx.x509.verifyCertificateChain({\n        trustedCertificates: trustedStatusCertificates,\n        x5chain,\n      })\n\n      const [certificate] = x5chain\n      const publicKey = await ctx.x509.getPublicKey({ certificate, algorithm: cwt.algorithm })\n\n      if (!(await cwt.verifySignature({ key: publicKey }, ctx.cose.sign1))) {\n        throw new InvalidIdentifierListSignatureError('Incorrect signature for CWT identifier list')\n      }\n\n      // Spec: revoked iff the MSO's identifier is present in the list.\n      if (cwt.includes(id)) {\n        const hex = Array.from(id, (b) => b.toString(16).padStart(2, '0')).join('')\n        throw new IdentifierFoundInRevokedListError(`Identifier ${hex} found in revoked list at ${uri}`)\n      }\n\n      identifierList = cwt\n      trustedIdentifierListChain = identifierChain\n    }\n\n    return { statusList, trustedStatusListChain, identifierList, trustedIdentifierListChain }\n  }\n\n  public async verify(\n    options: {\n      verificationCallback?: VerificationCallback\n      now?: Date\n      trustedCertificates?: Array<{ issuance: Uint8Array[]; status?: Uint8Array[] }>\n      disableCertificateChainValidation?: boolean\n      disableStatusValidation?: boolean\n      skewSeconds?: number\n    },\n    ctx: Pick<MdocContext, 'x509' | 'cose' | 'fetch'>\n  ): Promise<IssuerAuthVerificationResult> {\n    const verificationCallback = options.verificationCallback ?? defaultVerificationCallback\n    const now = options.now ?? new Date()\n    const disableCertificateChainValidation = options.disableCertificateChainValidation ?? false\n    const disableStatusValidation = options.disableStatusValidation ?? 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    let trustedStatusCertificates: Uint8Array[] | undefined\n    let trustedIssuanceChain: Uint8Array[] | undefined\n    if (!disableCertificateChainValidation) {\n      try {\n        if (!trustedCertificates || trustedCertificates?.length <= 0) {\n          throw new Error('No trusted certificates found. Cannot verify issuer signature.')\n        }\n\n        const { chain } = await ctx.x509.verifyCertificateChain({\n          trustedCertificates: trustedCertificates.flatMap(({ issuance }) => issuance),\n          x5chain: this.certificateChain,\n          now,\n        })\n\n        trustedIssuanceChain = chain\n        trustedStatusCertificates = chain[chain.length - 1]\n          ? trustedCertificates.find((tc) => tc.issuance.some((cert) => compareBytes(cert, chain[chain.length - 1])))\n              ?.status\n          : undefined\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    let statusList: StatusListCwt | undefined\n    let trustedStatusListChain: Uint8Array[] | undefined\n    let identifierList: IdentifierListCwt | undefined\n    let trustedIdentifierListChain: Uint8Array[] | undefined\n    if (!disableStatusValidation) {\n      try {\n        ;({ statusList, trustedStatusListChain, identifierList, trustedIdentifierListChain } = await this.verifyStatus(\n          {\n            now,\n            checkFreshness: true,\n            trustedStatusCertificates,\n          },\n          ctx\n        ))\n      } catch (err) {\n        onCheck({\n          status: 'FAILED',\n          check: 'Status information must be valid',\n          reason: err instanceof Error ? err.message : 'Unknown error',\n        })\n      }\n    }\n\n    const publicKey = await ctx.x509.getPublicKey({ certificate: this.certificate, algorithm: this.algorithm })\n    const isSignatureValid = await this.verifySignature({ key: publicKey }, ctx.cose.sign1)\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    onCheck({\n      status: trustedIssuanceChain ? 'PASSED' : 'FAILED',\n      check:\n        'Unable to determine a trusted issuance chain for the provided trusted certificates and the signer of the issuer auth',\n      reason:\n        'Unable to determine a trusted issuance chain for the provided trusted certificates and the signer of the issuer auth',\n    })\n\n    return {\n      trustedIssuanceChain: trustedIssuanceChain as Uint8Array[],\n      statusList,\n      trustedStatusListChain,\n      identifierList,\n      trustedIdentifierListChain,\n    }\n  }\n}\n","import { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { base64url } from '@owf/identity-common'\nimport { z } from 'zod'\nimport type { MdocContext } from '../../context'\nimport { defaultVerificationCallback, onCategoryCheck, type VerificationCallback } from '../check-callback'\nimport { IssuerAuth, type IssuerAuthEncodedStructure, type IssuerAuthVerificationResult } 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 type IssuerSignedVerificationResult = IssuerAuthVerificationResult\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: {\n      verificationCallback?: VerificationCallback\n      now?: Date\n      trustedCertificates?: Array<{ issuance: Uint8Array[]; status?: Uint8Array[] }>\n      disableCertificateChainValidation?: boolean\n      disableStatusValidation?: boolean\n      skewSeconds?: number\n    },\n    ctx: Pick<MdocContext, 'x509' | 'crypto' | 'cose' | 'fetch'>\n  ): Promise<IssuerSignedVerificationResult> {\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    // Verify the issuer auth\n    const { trustedIssuanceChain, statusList, trustedStatusListChain, identifierList, trustedIdentifierListChain } =\n      await this.issuerAuth.verify(options, ctx)\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    return { trustedIssuanceChain, statusList, trustedStatusListChain, identifierList, trustedIdentifierListChain }\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 { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\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 { CborStructure } from '@owf/cose'\nimport { z } from 'zod'\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 {\n  CborStructure,\n  type CoseKey,\n  ProtectedHeaders,\n  RegisteredCwtHeaderClaimKey,\n  TypedMap,\n  typedMap,\n  UnprotectedHeaders,\n} from '@owf/cose'\nimport { base64url, stringToBytes } from '@owf/identity-common'\nimport { z } from 'zod'\nimport type { MdocContext } from '../../context'\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 type { IssuerAuthVerificationResult } from './issuer-auth'\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 type DeviceResponseVerificationResult = Array<IssuerAuthVerificationResult & { document: Document }>\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      disableStatusValidation?: boolean\n      trustedCertificates: Array<{ issuance: Uint8Array[]; status?: Uint8Array[] }>\n      now?: Date\n      onCheck?: VerificationCallback\n      skewSeconds?: number\n    },\n    ctx: Pick<MdocContext, 'cose' | 'x509' | 'crypto' | 'fetch'>\n  ): Promise<DeviceResponseVerificationResult> {\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    const returnValue: DeviceResponseVerificationResult = []\n    for (const document of documents ?? []) {\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      const { trustedIssuanceChain, statusList, trustedStatusListChain, identifierList, trustedIdentifierListChain } =\n        await document.issuerSigned.verify(\n          {\n            verificationCallback: onCheck,\n            disableCertificateChainValidation: options.disableCertificateChainValidation,\n            now: options.now,\n            trustedCertificates: options.trustedCertificates,\n            skewSeconds: options.skewSeconds,\n            disableStatusValidation: options.disableStatusValidation,\n          },\n          ctx\n        )\n      returnValue.push({\n        trustedIssuanceChain,\n        statusList,\n        trustedStatusListChain,\n        identifierList,\n        trustedIdentifierListChain,\n        document,\n      })\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    return returnValue\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 = UnprotectedHeaders.create({})\n        if (signingKey.keyId) {\n          // COSE label 4 (kid) is a bstr per RFC 8152; UTF-8 encode\n          // the text form at the header boundary.\n          unprotectedHeaders.headers?.set(RegisteredCwtHeaderClaimKey.KeyId, stringToBytes(signingKey.keyId))\n        }\n\n        const protectedHeaders = ProtectedHeaders.create({\n          protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.Algorithm, signingKey.algorithm]]),\n        })\n\n        const deviceAuthOptions: DeviceAuthOptions = {}\n        if (useSignature) {\n          const deviceSignature = await DeviceSignature.create({\n            unprotectedHeaders,\n            protectedHeaders,\n            payload: null,\n          }).sign({ signingKey, detachedPayload: deviceAuthenticationBytes }, { sign: ctx.cose.sign1.sign })\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 = DeviceMac.create({\n            protectedHeaders,\n            unprotectedHeaders,\n            payload: null,\n          })\n\n          const macKey = await deviceMac.createDeviceMacKey(\n            {\n              publicKey: ephemeralKey,\n              privateKey: signingKey,\n              sessionTranscript: options.sessionTranscript,\n            },\n            ctx\n          )\n\n          await deviceMac.authenticate({ key: macKey, detachedPayload: deviceAuthenticationBytes }, ctx.cose.mac0)\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 { CborStructure } from '@owf/cose'\nimport z from 'zod'\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 { CborStructure } from '@owf/cose'\nimport z from 'zod'\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 {\n  type CoseKey,\n  type MacAlgorithm,\n  ProtectedHeaders,\n  RegisteredCwtHeaderClaimKey,\n  type SignatureAlgorithm,\n  UnprotectedHeaders,\n} from '@owf/cose'\nimport { stringToBytes } from '@owf/identity-common'\nimport type { MdocContext } from '../../context'\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    certificate: Uint8Array\n  }): Promise<DeviceSigned> {\n    const protectedHeaders = ProtectedHeaders.create({\n      protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.Algorithm, options.algorithm]]),\n    })\n\n    const unprotectedHeaders = UnprotectedHeaders.create({\n      unprotectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.X5Chain, [options.certificate]]]),\n    })\n\n    if (options.signingKey.keyId) {\n      // COSE label 4 (kid) is a bstr per RFC 8152; UTF-8 encode the\n      // text form at the header boundary.\n      unprotectedHeaders.headers?.set(RegisteredCwtHeaderClaimKey.KeyId, stringToBytes(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 = DeviceSignature.create({\n      unprotectedHeaders,\n      protectedHeaders,\n      payload: null,\n    })\n\n    await deviceSignature.sign(\n      {\n        signingKey: options.signingKey,\n        detachedPayload: deviceAuthentication.encode({ asDataItem: true }),\n      },\n      { sign: this.ctx.cose.sign1.sign }\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    certificate: Uint8Array\n  }): Promise<DeviceSigned> {\n    const protectedHeaders = ProtectedHeaders.create({\n      protectedHeaders: new Map<number, unknown>([[RegisteredCwtHeaderClaimKey.Algorithm, options.algorithm]]),\n    })\n\n    const unprotectedHeaders = UnprotectedHeaders.create({\n      unprotectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.X5Chain, [options.certificate]]]),\n    })\n\n    if (options.privateKey.keyId) {\n      // COSE label 4 (kid) is a bstr per RFC 8152; UTF-8 encode the\n      // text form at the header boundary.\n      protectedHeaders.headers?.set(RegisteredCwtHeaderClaimKey.KeyId, stringToBytes(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 = DeviceMac.create({\n      unprotectedHeaders,\n      protectedHeaders,\n      payload: null,\n    })\n\n    const salt = await this.ctx.crypto.digest({ digestAlgorithm: 'SHA-256', bytes: options.sessionTranscript.encode() })\n\n    const derivedKey = await this.ctx.crypto.hdkf({\n      privateKey: options.privateKey.privateKey,\n      publicKey: options.publicKey.publicKey,\n      info: stringToBytes('EMacKey'),\n      salt,\n    })\n\n    const deviceMacWithTag = await deviceMac.authenticate(\n      {\n        key: derivedKey,\n        detachedPayload: deviceAuthentication.encode({ asDataItem: true }),\n      },\n      this.ctx.cose.mac0\n    )\n\n    return DeviceSigned.create({\n      deviceNamespaces: this.namespaces,\n      deviceAuth: DeviceAuth.create({\n        deviceMac: deviceMacWithTag,\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  // ISO/IEC 18013-5 §12.3.4 mandates DigestID values smaller than 2^31. We mask\n  // off the most significant bit so the result stays in [0, 2^31 - 1] while\n  // preserving the full 31 bits of entropy.\n  return ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) & 0x7fffffff\n}\n","import {\n  type CoseKey,\n  type DigestAlgorithm,\n  ProtectedHeaders,\n  RegisteredCwtHeaderClaimKey,\n  type SignatureAlgorithm,\n  UnprotectedHeaders,\n} from '@owf/cose'\nimport { stringToBytes } from '@owf/identity-common'\nimport type { MdocContext } from '../../context'\nimport { randomUnsignedInteger } from '../../utils/randomUnsignedInteger'\nimport { AtLeastOneCertificateRequiredError, SignatureAlgorithmDoesNotMatchSigningKeyAlgorithmError } from '../errors'\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  Status,\n  type StatusOptions,\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    certificates: Uint8Array[]\n    /**\n     * Optional Status structure to embed in the MSO. See\n     * ISO/IEC 18013-5 second edition (CD), 12.3.6. Allows the issuer to\n     * publish revocation information via a status list and/or identifier\n     * list referenced from inside the signed MSO.\n     */\n    status?: Status | StatusOptions\n  }): Promise<IssuerSigned> {\n    if (options.signingKey.algorithm && options.signingKey.algorithm !== options.algorithm) {\n      throw new SignatureAlgorithmDoesNotMatchSigningKeyAlgorithmError(\n        `Signing key algorithm '${options.signingKey.algorithm}' does not match the supplied algorithm '${options.algorithm}'`\n      )\n    }\n\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    if (options.certificates.length === 0) {\n      throw new AtLeastOneCertificateRequiredError(\n        'At least one certificate (the document signer certificate) must be provided.'\n      )\n    }\n\n    const status =\n      options.status === undefined\n        ? undefined\n        : options.status instanceof Status\n          ? options.status\n          : Status.create(options.status)\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      status,\n    })\n\n    const protectedHeaders = ProtectedHeaders.create({\n      protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.Algorithm, options.algorithm]]),\n    })\n\n    const unprotectedHeaders = UnprotectedHeaders.create({\n      unprotectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.X5Chain, options.certificates]]),\n    })\n\n    if (options.signingKey.keyId) {\n      // COSE label 4 (kid) is a bstr per RFC 8152; CoseKey.keyId is the\n      // text form, so we UTF-8 encode here at the header boundary.\n      unprotectedHeaders.headers?.set(RegisteredCwtHeaderClaimKey.KeyId, stringToBytes(options.signingKey.keyId))\n    }\n\n    const issuerAuth = await IssuerAuth.create({\n      payload: mso,\n      unprotectedHeaders,\n      protectedHeaders,\n    }).sign(\n      { signingKey: options.signingKey, algorithm: options.algorithm },\n      {\n        sign: this.ctx.cose.sign1.sign,\n      }\n    )\n\n    return IssuerSigned.create({\n      issuerNamespaces: this.namespaces,\n      issuerAuth,\n    })\n  }\n}\n","import type { CoseKey } from '@owf/cose'\nimport { base64url } from '@owf/identity-common'\nimport type { MdocContext } from './context'\nimport {\n  type DeviceNamespaces,\n  DeviceRequest,\n  DeviceResponse,\n  IssuerSigned,\n  type IssuerSignedVerificationResult,\n  SessionTranscript,\n  type VerificationCallback,\n} from './mdoc'\n\nexport class Holder {\n  /**\n   *\n   * string should be base64url encoded as defined in openid4vci\n   *\n   */\n  public static async verifyIssuerSigned(\n    options: {\n      issuerSigned: Uint8Array | string | IssuerSigned\n      verificationCallback?: VerificationCallback\n      now?: Date\n      disableCertificateChainValidation?: boolean\n      disableStatusValidation?: boolean\n      trustedCertificates?: Array<{ issuance: Uint8Array[]; status?: Uint8Array[] }>\n      skewSeconds?: number\n    },\n    ctx: Pick<MdocContext, 'cose' | 'x509' | 'crypto' | 'fetch'>\n  ): Promise<IssuerSignedVerificationResult> {\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    return await issuerSigned.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       * Trust anchors for the reader's certificate chain. When provided, each\n       * `DocRequest.readerAuth` chain is validated against these anchors (e.g.\n       * CAs listed in a RICAL — Reader Identification CA List, defined in\n       * ISO/IEC 18013-5 second edition Annex F).\n       *\n       * When omitted, reader-auth signatures are verified but chain trust is\n       * not established — equivalent to first-edition behaviour.\n       */\n      trustedCertificates?: Array<Uint8Array>\n      /**\n       * Reference time for certificate `notBefore`/`notAfter` checks during\n       * chain validation. Defaults to the current time.\n       */\n      now?: Date\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          trustedCertificates: options.trustedCertificates,\n          now: options.now,\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 { CoseKey, type DigestAlgorithm, type SignatureAlgorithm } from '@owf/cose'\nimport type { MdocContext } from './context'\nimport type {\n  DeviceKeyInfo,\n  DeviceKeyInfoOptions,\n  DocType,\n  IssuerSigned,\n  Namespace,\n  Status,\n  StatusOptions,\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    certificates: Uint8Array[]\n    /**\n     * Optional Status structure to embed in the MSO. See\n     * ISO/IEC 18013-5 second edition (CD), 12.3.6.\n     */\n    status?: Status | StatusOptions\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 { CoseKey } from '@owf/cose'\nimport type { MdocContext } from './context.js'\nimport type { VerificationCallback } from './mdoc/check-callback.js'\nimport {\n  type DeviceRequest,\n  DeviceResponse,\n  type DeviceResponseVerificationResult,\n  type SessionTranscript,\n} 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      disableStatusValidation?: boolean\n      trustedCertificates: Array<{ issuance: Uint8Array[]; status?: Uint8Array[] }>\n      now?: Date\n      onCheck?: VerificationCallback\n      skewSeconds?: number\n    },\n    ctx: Pick<MdocContext, 'cose' | 'x509' | 'crypto' | 'fetch'>\n  ): Promise<DeviceResponseVerificationResult> {\n    const deviceResponse =\n      options.deviceResponse instanceof DeviceResponse\n        ? options.deviceResponse\n        : DeviceRespon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