@owf/mdoc 0.8.2 → 0.8.3-alpha-20261008081905
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +3 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["z","cborDecode","cborEncode","z","z","z","z","z","CoseKey","z","z","z","z","z","CoseKey","cborEncode","cborEncode","cborEncode","z","z","Mac0","Sign1","z","CoseKey","z","z","z","z","z","Sign1","z","z","z","z","StatusListInfo","z","z","z","RegisteredCwtHeaderClaimKey","ProtectedHeaders","z","RegisteredCwtClaimKey","ProtectedHeaders","RegisteredCwtHeaderClaimKey","RegisteredCwtHeaderClaimKey","RegisteredCwtClaimKey","Sign1","cborDecode","z","z","z","z","z","z","UnprotectedHeaders","RegisteredCwtHeaderClaimKey","ProtectedHeaders","z","z","CoseKey","z","ProtectedHeaders","RegisteredCwtHeaderClaimKey","UnprotectedHeaders","ProtectedHeaders","RegisteredCwtHeaderClaimKey","UnprotectedHeaders","z","UnprotectedHeaders","RegisteredCwtHeaderClaimKey","ProtectedHeaders","KeyType","Curve","CoseKey"],"sources":["../src/context.ts","../src/mdoc/errors.ts","../src/mdoc/models/ble-options.ts","../src/utils/keyAuthorizations.ts","../src/mdoc/check-callback.ts","../src/utils/cbor.ts","../src/mdoc/original-bytes-cbor-structure.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/engagement-to-app-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/utils/ageOver.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/getOwnProperty.ts","../src/utils/version.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/identifier-list-cwt-headers.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/mso-revocation-list.ts","../src/mdoc/models/issuer-auth.ts","../src/mdoc/models/issuer-signed-item.ts","../src/mdoc/models/issuer-namespaces.ts","../src/mdoc/models/issuer-signed.ts","../src/utils/matchDeviceRequest.ts","../src/mdoc/models/device-signed.ts","../src/mdoc/models/error-items.ts","../src/mdoc/models/errors.ts","../src/mdoc/models/document.ts","../src/mdoc/models/document-error.ts","../src/mdoc/models/device-response.ts","../src/mdoc/models/encrypted-response-data.ts","../src/mdoc/models/encrypted-response.ts","../src/mdoc/models/encryption-parameters.ts","../src/mdoc/models/encryption-info.ts","../src/mdoc/builders/device-signed-builder.ts","../src/utils/randomUnsignedInteger.ts","../src/utils/x5chain.ts","../src/mdoc/builders/issuer-signed-builder.ts","../src/holder.ts","../src/iso-mdoc-dc-api.ts","../src/issuer.ts","../src/verifier.ts"],"sourcesContent":["import type { CoseKey, DigestAlgorithm, Mac0Context, MacAlgorithm, Sign1Context, SignatureAlgorithm } from '@owf/cose'\n\ntype MaybePromise<T> = Promise<T> | T\n\n/**\n * HPKE (RFC 9180) cipher suites, identified as `<kem>/<kdf>/<aead>`.\n *\n * ISO/IEC TS 18013-7:2025 C.4 fixes the DC API suite to\n * {@link HpkeSuiteId.DhkemP256HkdfSha256HkdfSha256Aes128Gcm}; the other members exist so the same\n * callbacks can be reused by protocols that negotiate a suite.\n */\nexport enum HpkeSuiteId {\n /** DHKEM(P-256, HKDF-SHA256) / HKDF-SHA256 / AES-128-GCM. */\n DhkemP256HkdfSha256HkdfSha256Aes128Gcm = 'dhkem-p256-hkdf-sha256/hkdf-sha256/aes-128-gcm',\n\n /** DHKEM(P-256, HKDF-SHA256) / HKDF-SHA256 / AES-256-GCM. */\n DhkemP256HkdfSha256HkdfSha256Aes256Gcm = 'dhkem-p256-hkdf-sha256/hkdf-sha256/aes-256-gcm',\n\n /** DHKEM(X25519, HKDF-SHA256) / HKDF-SHA256 / AES-128-GCM. */\n DhkemX25519HkdfSha256HkdfSha256Aes128Gcm = 'dhkem-x25519-hkdf-sha256/hkdf-sha256/aes-128-gcm',\n}\n\nexport interface HpkeContext {\n /**\n * Suites the `seal` and `open` implementations support. Callers check this before use so an\n * unsupported suite surfaces as a protocol error instead of a callback failure.\n */\n suites: Array<HpkeSuiteId>\n\n /**\n * Single-shot HPKE seal in base mode (RFC 9180 §6.1).\n */\n seal: (input: {\n suite: HpkeSuiteId\n recipientPublicKey: CoseKey\n info: Uint8Array\n aad?: Uint8Array\n plaintext: Uint8Array\n }) => MaybePromise<{ enc: Uint8Array; ciphertext: Uint8Array }>\n\n /**\n * Single-shot HPKE open in base mode (RFC 9180 §6.1). `enc` is the raw serialized encapsulated\n * key for the suite's KEM (uncompressed SEC1 point for the DHKEM(P-256) suites).\n */\n open: (input: {\n suite: HpkeSuiteId\n /**\n * The recipient key. Implementations that keep private keys inside a key management system are\n * passed the public key and resolve the associated private key based on its `keyId`, the same\n * way {@link Sign1Context.sign} resolves a signing key.\n */\n recipientKey: CoseKey\n enc: Uint8Array\n info: Uint8Array\n aad?: Uint8Array\n ciphertext: Uint8Array\n }) => MaybePromise<Uint8Array>\n}\n\nexport interface MdocContext {\n fetch: typeof fetch\n crypto: {\n random: (length: number) => Uint8Array\n digest: (input: { digestAlgorithm: DigestAlgorithm; bytes: Uint8Array }) => MaybePromise<Uint8Array>\n hdkf: (input: {\n digestAlgorithm?: DigestAlgorithm\n privateKey: Uint8Array\n publicKey: Uint8Array\n salt: Uint8Array\n info: Uint8Array\n }) => MaybePromise<Uint8Array>\n\n /**\n * Required for the ISO 18013-7 Annex C (`org-iso-mdoc`) DC API flows only.\n */\n hpke?: HpkeContext\n }\n\n cose: {\n sign1: {\n sign: Sign1Context['sign']\n verify: Sign1Context['verify']\n }\n\n mac0: Mac0Context\n }\n\n x509: {\n /**\n * The values of a field of the subject distinguished name of a certificate, e.g. `C` or `ST`.\n */\n getSubjectNameField: (options: { certificate: Uint8Array; field: string }) => string[]\n getPublicKey: (options: {\n certificate: Uint8Array\n algorithm?: SignatureAlgorithm | MacAlgorithm\n }) => Promise<CoseKey>\n\n /**\n * Verify a X.509 certificate chain, returning it with the leaf first and the trusted root last.\n */\n verifyCertificateChain: (input: {\n trustedCertificates: Uint8Array[]\n x5chain: Uint8Array[]\n now?: Date\n }) => MaybePromise<{ chain: Uint8Array[] }>\n\n getCertificateData: (input: { certificate: Uint8Array }) => MaybePromise<{\n issuerName: string\n subjectName: string\n serialNumber: string\n thumbprint: string\n notBefore: Date\n notAfter: Date\n pem: string\n }>\n }\n}\n","import type { VerificationAssessment, VerificationCallback } from './check-callback.js'\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 {}\n\n/**\n * ISO/IEC 18013-5 9.1.3.4 forbids an mdoc from authenticating device-signed elements its device key\n * is not authorized for in the MSO's `KeyAuthorizations`. Creating such a response would produce\n * one every conformant mdoc reader has to reject, so it is refused up front.\n */\nexport class DeviceKeyNotAuthorizedError extends MdlError {}\n\n/**\n * An element to disclose in a device response is requested, but the document cannot disclose it:\n * the issuer did not sign it, and no device-signed value the device key is authorized for was\n * provided.\n */\nexport class MissingRequestedElementError extends MdlError {}\n\n/**\n * The elements selected for disclosure in a device response do not fit the doc request: an element\n * is selected that the doc request does not ask for, or a selected element is answered with the same\n * age attestation as a requested element that is left out.\n */\nexport class InvalidElementSelectionError extends MdlError {}\n\n/**\n * A credential is used to answer a doc request for another docType: the docType of its mobile\n * security object is not the docType the doc request asks for.\n */\nexport class DocTypeMismatchError extends MdlError {}\n\n/**\n * ISO/IEC 18013-5 7.2.5: \"an mDL reader shall not request more than two age_over_NN data elements\".\n * Thrown when creating an items request that asks for more than two in a namespace, and when a\n * device response would disclose more than two in a namespace, as together they narrow down the age\n * of the holder.\n */\nexport class AgeOverLimitExceededError extends MdlError {}\n\n/**\n * The options to match a device request with do not fit the device request: they refer to a doc\n * request the device request does not have, or to the same doc request more than once.\n */\nexport class InvalidDeviceRequestMatchOptionsError extends MdlError {}\nexport class AtLeastOneCertificateRequiredError extends MdlError {}\n\n/**\n * ISO/IEC 18013-5 8.3.2.1.2.2: a namespace must not have two or more elements with the same element\n * identifier.\n */\nexport class DuplicateElementIdentifierError extends MdlError {}\n\n/**\n * ISO/IEC 18013-5 9.1.2.4: \"The validFrom element shall be equal or later than the signed element\",\n * and \"the validUntil element shall be later than the validFrom element\".\n */\nexport class InvalidValidityInfoError extends MdlError {}\n\n/**\n * ISO/IEC 18013-5 9.1.3.5: the device MAC shall use HMAC 256/256.\n */\nexport class UnsupportedDeviceMacAlgorithmError extends MdlError {}\nexport class SignatureAlgorithmDoesNotMatchSigningKeyAlgorithmError extends MdlError {}\nexport class UnableToExtractX5ChainFromCwtError extends MdlError {}\nexport class NoPublicKeySetOnStatusListError extends MdlError {}\nexport class InvalidSignatureError extends MdlError {}\n\n/**\n * ISO/IEC 18013-5 second edition § 12.3.6.3 requires the status list of an MSO to be a Status List\n * Token in CWT format, \"since the IssuerAuth structure is a CWT\". A list served as a JWT is a\n * deviation, and is rejected rather than verified.\n */\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\n/**\n * An MSO revocation list — status list or identifier list — was well-formed and correctly\n * signed, but one of the claim requirements from ISO/IEC 18013-5 second edition 12.3.6 /\n * the Token Status List specification was not met (missing or mismatched subject, missing\n * or passed expiration, or an issuance time in the future).\n */\nexport class InvalidRevocationListError extends MdlError {}\n\n/**\n * ISO/IEC TS 18013-7:2025 C.5 requires the mdoc to abort when the DC API did not provide an origin,\n * as the session transcript — and thus the anti-relay binding — cannot be computed without it.\n */\nexport class MissingOriginError extends MdlError {}\n\n/**\n * The origin is not an origin as the DC API provides it: the ASCII serialization of an origin\n * (`scheme://host[:port]`), without a path, a trailing slash or a default port. The session transcript\n * binds the exact origin, so any other form would not match the origin the other party uses.\n */\nexport class InvalidOriginError extends MdlError {}\nexport class HpkeNotSupportedError extends MdlError {}\n\n/**\n * The request or response payload handed over the DC API did not have the shape Annex C defines.\n */\nexport class InvalidDcApiRequestError extends MdlError {}\nexport class InvalidDcApiResponseError extends MdlError {}\nexport class InvalidEncryptionInfoError extends MdlError {}\nexport class InvalidEncryptedResponseError extends MdlError {}\n\n/**\n * A verification check failed.\n *\n * Verification reports every check it runs through a {@link VerificationCallback}; the default\n * callback turns the first `FAILED` check into this error. `assessment` is that check, including\n * the structured `result` of the checks that produce one, so that a caller which does not collect\n * the checks itself does not have to parse the message to learn what failed.\n */\nexport class VerificationError extends MdlError {\n public readonly assessment: VerificationAssessment\n\n public constructor(message: string, assessment: VerificationAssessment) {\n super(message)\n this.assessment = assessment\n }\n}\n","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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\n return this.fromEncodedStructure(map)\n }\n}\n","import type { DataElementIdentifier } from '../mdoc/models/data-element-identifier'\nimport type { DeviceNamespaces } from '../mdoc/models/device-namespaces'\nimport type { KeyAuthorizations } from '../mdoc/models/key-authorizations'\nimport type { Namespace } from '../mdoc/models/namespace'\n\nexport type DeviceSignedElement = {\n namespace: Namespace\n elementIdentifier: DataElementIdentifier\n}\n\n/**\n * The data elements the mdoc authenticated through `DeviceNameSpaces`, flattened across namespaces.\n */\nexport const collectDeviceSignedElements = (deviceNamespaces?: DeviceNamespaces): Array<DeviceSignedElement> =>\n Array.from(deviceNamespaces?.deviceNamespaces ?? []).flatMap(([namespace, deviceSignedItems]) =>\n Array.from(deviceSignedItems.deviceSignedItems.keys()).map((elementIdentifier) => ({\n namespace,\n elementIdentifier,\n }))\n )\n\n/**\n * Whether the device key is authorized to authenticate a device-signed element, either for its\n * whole namespace or for the data element itself (18013-5 9.1.2.4).\n */\nexport const isDeviceSignedElementAuthorized = (\n keyAuthorizations: KeyAuthorizations | undefined,\n { namespace, elementIdentifier }: DeviceSignedElement\n) =>\n (keyAuthorizations?.namespaces?.includes(namespace) ||\n keyAuthorizations?.dataElements?.get(namespace)?.includes(elementIdentifier)) ??\n false\n\n/**\n * The device-signed elements the device key is not authorized to authenticate.\n *\n * ISO/IEC 18013-5 9.1.3.4: \"An mdoc shall only authenticate response data elements in\n * `DeviceNameSpaces` if the key it is using for mdoc authentication is authorized to authenticate\n * these elements in the `KeyAuthorizations` structure in the MSO. The mdoc reader shall validate\n * this authorization as part of validating the mdoc authentication.\" Authorization is given either\n * for a whole namespace or per data element (9.1.2.4), so both sides run this: the mdoc before it\n * signs or MACs a response, the mdoc reader after it decodes one.\n */\nexport const findUnauthorizedDeviceSignedElements = (options: {\n deviceNamespaces?: DeviceNamespaces\n keyAuthorizations?: KeyAuthorizations\n}): Array<DeviceSignedElement> =>\n collectDeviceSignedElements(options.deviceNamespaces).filter(\n (element) => !isDeviceSignedElementAuthorized(options.keyAuthorizations, element)\n )\n\n/**\n * A shared description of unauthorized elements, so the mdoc's error and the mdoc reader's failed\n * check name the same elements in the same way.\n */\nexport const describeUnauthorizedDeviceSignedElements = (unauthorized: Array<DeviceSignedElement>) =>\n `The device key is not authorized to authenticate ${unauthorized\n .map(({ namespace, elementIdentifier }) => `'${elementIdentifier}' in namespace '${namespace}'`)\n .join(', ')}`\n","import type { DeviceRequestMatchResult } from '../utils/matchDeviceRequest.js'\nimport { VerificationError } from './errors.js'\n\n/**\n * The structured result of a check that has more to report than a reason string, discriminated by\n * `type`. A check that produces one attaches it to its {@link VerificationAssessment}, so that it\n * reaches both a callback that collects the checks and the {@link VerificationError} the default\n * callback throws.\n */\nexport type VerificationAssessmentResult = {\n type: 'deviceRequestMatch'\n match: DeviceRequestMatchResult\n}\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 * The structured result of the check, for the checks that produce one.\n */\n result?: VerificationAssessmentResult\n}\n\nexport type VerificationCallback = (item: VerificationAssessment) => void\n\nexport const defaultVerificationCallback: VerificationCallback = (verification) => {\n if (verification.status !== 'FAILED') return\n throw new VerificationError(verification.reason ?? verification.check, verification)\n}\n\nexport const onCategoryCheck = (onCheck: VerificationCallback, category: VerificationAssessment['category']) => {\n return (item: Omit<VerificationAssessment, 'category'>) => {\n onCheck({ ...item, category })\n }\n}\n","import { cborDecode, DataItem } from '@owf/cose'\n\n/**\n * The bytes of an encoded structure, without the tag 24 (encoded CBOR data item) it may be wrapped in.\n */\nexport const unwrapDataItemBytes = (bytes: Uint8Array) => {\n const decoded = cborDecode(bytes, { unwrapTopLevelDataItem: false })\n return new Uint8Array(decoded instanceof DataItem ? decoded.buffer : bytes)\n}\n","import {\n type AnyCborStructure,\n type CborEncodeOptions,\n CborStructure,\n type CborStructureStaticThis,\n cborEncode,\n DataItem,\n TypedMap,\n} from '@owf/cose'\nimport { unwrapDataItemBytes } from '../utils/cbor'\n\n/**\n * A CBOR structure that keeps the bytes it was decoded from, and encodes with them until it is\n * modified.\n *\n * ISO/IEC 18013-5 8.1: \"the bytestrings shall be used as they are sent or received\". Structures that\n * are embedded as bytes in a signed, MACed or hashed structure are therefore embedded as received, as\n * re-encoding the decoded structure may give other bytes, for instance for floats, tag 0 dates with\n * fractional seconds, indefinite lengths or non-shortest encodings of another encoder.\n *\n * The bytes are kept when the structure is decoded with {@link decode} or {@link fromDataItem}, so a\n * parent structure has to decode it from its data item with `fromDataItem`, and embed it with\n * {@link asDataItem}.\n *\n * Setting or deleting an entry of a structure that is a `TypedMap` drops the bytes on its own. Call\n * {@link markModified} after changing the structure in any other way, such as a nested value.\n */\nexport class OriginalBytesCborStructure<\n EncodedStructure = unknown,\n DecodedStructure = EncodedStructure,\n> extends CborStructure<EncodedStructure, DecodedStructure> {\n #originalBytes?: Uint8Array\n\n public constructor(structure: DecodedStructure) {\n super(structure)\n\n if (structure instanceof TypedMap) {\n structure.onChange = () => this.markModified()\n }\n }\n\n /**\n * The bytes this structure was decoded from, without tag 24, if it was decoded and has not been\n * modified since.\n */\n public get originalBytes() {\n return this.#originalBytes\n }\n\n /**\n * Drops the {@link originalBytes}, so that the structure is re-encoded the next time it is encoded.\n */\n public markModified() {\n this.#originalBytes = undefined\n }\n\n /**\n * Accepts the encoded structure as well as the structure wrapped in tag 24.\n */\n public static override decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n // biome-ignore lint/complexity/noThisInStatic: `super.decode` keeps `this` bound to the subclass\n const structure = super.decode(bytes) as T\n\n if (structure instanceof OriginalBytesCborStructure) {\n structure.#originalBytes = unwrapDataItemBytes(bytes)\n }\n\n return structure\n }\n\n public static override fromDataItem<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n dataItem: unknown\n ): T {\n // biome-ignore lint/complexity/noThisInStatic: `super.fromDataItem` keeps `this` bound to the subclass\n const structure = super.fromDataItem(dataItem) as T\n\n if (structure instanceof OriginalBytesCborStructure && dataItem instanceof DataItem) {\n structure.#originalBytes = new Uint8Array(dataItem.buffer)\n }\n\n return structure\n }\n\n public override encode(options?: CborEncodeOptions): Uint8Array {\n if (!this.#originalBytes) return super.encode(options)\n\n return options?.asDataItem ? cborEncode(this.asDataItem) : this.#originalBytes\n }\n\n /**\n * This structure as a tag 24 data item, with the bytes it was received as if it was decoded.\n */\n public get asDataItem(): DataItem<EncodedStructure> {\n return DataItem.fromBuffer<EncodedStructure>(this.encode())\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\n return this.fromEncodedStructure(options.deviceSignedItems)\n }\n}\n","import { z } from 'zod'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport type { DataElementValue } from './data-element-value'\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 OriginalBytesCborStructure<\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 /**\n * The device namespaces. Call {@link markModified} after changing them in place, or use\n * {@link setDeviceNamespace} and {@link setDeviceSignedElement}.\n */\n public get deviceNamespaces() {\n return this.structure\n }\n\n public getDeviceNamespace(namespace: Namespace) {\n return this.structure.get(namespace)\n }\n\n public setDeviceNamespace(namespace: Namespace, deviceSignedItems: DeviceSignedItems) {\n this.structure.set(namespace, deviceSignedItems)\n this.markModified()\n }\n\n /**\n * Sets an element in a namespace, and adds the namespace if it is not there yet.\n */\n public setDeviceSignedElement(\n namespace: Namespace,\n elementIdentifier: DataElementIdentifier,\n elementValue: DataElementValue\n ) {\n const deviceSignedItems = this.structure.get(namespace)\n\n if (deviceSignedItems) {\n deviceSignedItems.deviceSignedItems.set(elementIdentifier, elementValue)\n this.markModified()\n } else {\n this.setDeviceNamespace(\n namespace,\n DeviceSignedItems.create({ deviceSignedItems: new Map([[elementIdentifier, elementValue]]) })\n )\n }\n }\n\n public static create(options: DeviceNamespacesOptions): DeviceNamespaces {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import { TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\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 // 18013-5 8.2.1.1: ServerRetrievalMethods = { ? \"webApi\" : WebApi, ? \"oidc\" : Oidc }, a single map.\n [DeviceEngagementKeys.ServerRetrievalMethods, 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?: ServerRetrievalMethod\n protocolInfo?: ProtocolInfo\n}\n\nexport class DeviceEngagement extends OriginalBytesCborStructure<\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 map.set(\n DeviceEngagementKeys.ServerRetrievalMethods,\n ServerRetrievalMethod.fromEncodedStructure(\n input.get(DeviceEngagementKeys.ServerRetrievalMethods) as ServerRetrievalMethodEncodedStructure\n )\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(DeviceEngagementKeys.ServerRetrievalMethods, serverRetrievalMethods.encodedStructure)\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: DeviceEngagementDecodedStructure = new TypedMap([\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import {\n type AnyCborStructure,\n type CborEncodeOptions,\n type CborStructureStaticThis,\n CoseKey,\n type CoseKeyDecodedStructure,\n type CoseKeyEncodedStructure,\n type CoseKeyOptions,\n cborEncode,\n DataItem,\n} from '@owf/cose'\nimport { unwrapDataItemBytes } from '../../utils/cbor'\n\nexport type EReaderKeyDecodedStructure = CoseKeyDecodedStructure\nexport type EReaderKeyEncodedStructure = CoseKeyEncodedStructure\nexport type EReaderKeyOptions = CoseKeyOptions\n\n/**\n * A `CoseKey` for the ephemeral key of the mdoc reader, which keeps the bytes it was decoded from the\n * way `OriginalBytesCborStructure` does, as `EReaderKeyBytes` are part of the session transcript\n * (18013-5 8.1). It extends `CoseKey`, so it cannot extend `OriginalBytesCborStructure`.\n */\nexport class EReaderKey extends CoseKey {\n #originalBytes?: Uint8Array\n\n public static override create(options: EReaderKeyOptions): EReaderKey {\n // biome-ignore lint/complexity/noThisInStatic: `super.create` keeps `this` bound to the subclass\n return super.create(options) as EReaderKey\n }\n\n public static override fromJwk(jwk: Record<string, unknown>): EReaderKey {\n // biome-ignore lint/complexity/noThisInStatic: `super.fromJwk` keeps `this` bound to the subclass\n return super.fromJwk(jwk) as EReaderKey\n }\n\n /**\n * The bytes this reader key was decoded from, if it was decoded. A decoded reader key encodes as it\n * was received, as `EReaderKeyBytes` are part of the session transcript (18013-5 8.1).\n */\n public get originalBytes() {\n return this.#originalBytes\n }\n\n public static override decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n // biome-ignore lint/complexity/noThisInStatic: `super.decode` keeps `this` bound to the subclass\n const eReaderKey = super.decode(bytes) as unknown as T\n if (eReaderKey instanceof EReaderKey) eReaderKey.#originalBytes = unwrapDataItemBytes(bytes)\n return eReaderKey\n }\n\n public static override fromDataItem<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n dataItem: unknown\n ): T {\n // biome-ignore lint/complexity/noThisInStatic: `super.fromDataItem` keeps `this` bound to the subclass\n const eReaderKey = super.fromDataItem(dataItem) as unknown as T\n if (eReaderKey instanceof EReaderKey && dataItem instanceof DataItem) {\n eReaderKey.#originalBytes = new Uint8Array(dataItem.buffer)\n }\n return eReaderKey\n }\n\n public override encode(options?: CborEncodeOptions): Uint8Array {\n if (!this.#originalBytes) return super.encode(options)\n return options?.asDataItem ? cborEncode(this.asDataItem) : this.#originalBytes\n }\n\n /**\n * This reader key as a tag 24 data item, with the bytes it was received as if it was decoded.\n */\n public get asDataItem(): DataItem<EReaderKeyEncodedStructure> {\n return DataItem.fromBuffer<EReaderKeyEncodedStructure>(this.encode())\n }\n}\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 public get requiresReaderKey() {\n return false\n }\n\n public get requiresDeviceEngagement() {\n return false\n }\n}\n","import { zUint8Array } from '@owf/cose'\nimport type z from 'zod'\nimport { Handover } from './handover'\n\nconst engagementToAppHandoverSchema = zUint8Array\nexport type EngagementToAppHandoverStructure = z.infer<typeof engagementToAppHandoverSchema>\n\n/**\n * The handover of ISO/IEC TS 18013-7 Annex A, device retrieval to a website.\n *\n * A.8 defines it as a bare byte string:\n *\n * Handover = EngagementToApp / any\n * EngagementToApp = ReaderEngagementBytesHash\n * ReaderEngagementBytesHash = bstr\n * ReaderEngagementBytes = #6.24(bstr .cbor ReaderEngagement)\n *\n * where the hash is SHA-256 of ReaderEngagementBytes. Computing it is the\n * caller's business, since only the reader and the mdoc hold the\n * ReaderEngagement; this class is the CBOR shape.\n *\n * It is the only handover that is not a tuple or null, so it can never be\n * confused with one of the others when a SessionTranscript is decoded.\n */\nexport class EngagementToAppHandover extends Handover<EngagementToAppHandoverStructure> {\n public static override get encodingSchema() {\n return engagementToAppHandoverSchema\n }\n\n public get readerEngagementBytesHash() {\n return this.structure\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(readerEngagementBytesHash: Uint8Array) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(readerEngagementBytesHash)\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 { EngagementToAppHandover } from './engagement-to-app-handover'\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 // Last because it is the least specific: a bare bstr. None of the\n // others can match one, so the position is a readability choice\n // rather than a correctness one.\n EngagementToAppHandover,\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.fromDataItem(deviceEngagementDataItem)\n : null\n const eReaderKey = eReaderKeyDataItem ? EReaderKey.fromDataItem(eReaderKeyDataItem) : 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 // DeviceEngagementBytes and EReaderKeyBytes are embedded as received.\n deviceEngagement ? deviceEngagement.asDataItem : null,\n eReaderKey ? eReaderKey.asDataItem : 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 /**\n * A session transcript passed as bytes is either `SessionTranscript` or `SessionTranscriptBytes`\n * (tagged with tag 24).\n */\n public static from(sessionTranscript: SessionTranscript | Uint8Array): SessionTranscript {\n return sessionTranscript instanceof SessionTranscript\n ? sessionTranscript\n : SessionTranscript.decode(sessionTranscript)\n }\n\n public static create(options: SessionTranscriptOptions): SessionTranscript {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 returns the identical bytes.\n */\n public static forQrHandover(options: { deviceEngagement: DeviceEngagement; eReaderKey: EReaderKey }) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure({\n deviceEngagement: options.deviceEngagement,\n eReaderKey: options.eReaderKey,\n handover: QrHandover.create(),\n })\n }\n\n /**\n * Create a SessionTranscript for ISO/IEC TS 18013-7 Annex A, device\n * retrieval to a website.\n *\n * `readerEngagementBytesHash` is SHA-256 of\n * `#6.24(bstr .cbor ReaderEngagement)`, per A.8. As with QR handover the\n * exact CBOR bytes matter for session key derivation, so pass a\n * DeviceEngagement and an EReaderKey obtained through `decode()`.\n */\n public static forEngagementToApp(options: {\n deviceEngagement: DeviceEngagement\n eReaderKey: EReaderKey\n readerEngagementBytesHash: Uint8Array\n }) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure({\n deviceEngagement: options.deviceEngagement,\n eReaderKey: options.eReaderKey,\n handover: EngagementToAppHandover.create(options.readerEngagementBytesHash),\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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.fromDataItem(deviceNamespacesDataItem),\n }),\n encode: ({ sessionTranscript, docType, deviceNamespaces }) =>\n [\n 'DeviceAuthentication',\n sessionTranscript.encodedStructure,\n docType,\n // `DeviceNameSpacesBytes` are authenticated as the mdoc sent them (18013-5 8.1).\n deviceNamespaces.asDataItem,\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure({\n sessionTranscript: SessionTranscript.from(options.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 // biome-ignore lint/complexity/noThisInStatic: `super.create` keeps `this` bound to the subclass\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 // 18013-5 9.1.3.5: the salt is SHA-256(SessionTranscriptBytes), so the transcript tagged with tag 24.\n salt: await ctx.crypto.digest({\n digestAlgorithm: 'SHA-256',\n bytes: SessionTranscript.from(options.sessionTranscript).encode({ asDataItem: true }),\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 {\n collectDeviceSignedElements,\n describeUnauthorizedDeviceSignedElements,\n findUnauthorizedDeviceSignedElements,\n} from '../../utils/keyAuthorizations'\nimport {\n defaultVerificationCallback,\n onCategoryCheck,\n type VerificationAssessment,\n type VerificationCallback,\n} 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)\n\n// ISO/IEC 18013-5 9.1.3.4: DeviceAuth = { \"deviceSignature\" : DeviceSignature // \"deviceMac\" : DeviceMac }\n// The refinement is applied to the decoded schema, as both decoding and `fromDecodedStructure` validate against it.\nconst deviceAuthDecodedSchema = deviceAuthSchema.out.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, deviceAuthDecodedSchema, {\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 this.verifyKeyAuthorizations(options.document, onCheck)\n\n const deviceMac = this.structure.get('deviceMac')\n const deviceSignature = this.structure.get('deviceSignature')\n\n // The schema already enforces this, but a signature must never be accepted while a MAC is also present\n const hasExactlyOneAuthentication = (deviceSignature === undefined) !== (deviceMac === undefined)\n onCheck({\n status: hasExactlyOneAuthentication ? 'PASSED' : 'FAILED',\n check: 'Device Auth must contain either a deviceSignature or deviceMac element, but not both',\n })\n if (!hasExactlyOneAuthentication) {\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 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\n /**\n * The mdoc reader half of the ISO/IEC 18013-5 9.1.3.4 key authorization rule, which\n * {@link findUnauthorizedDeviceSignedElements} states in full. `DeviceResponse` enforces the\n * mdoc half of the same rule when it creates a response.\n */\n private verifyKeyAuthorizations(\n document: Document,\n onCheck: (item: Omit<VerificationAssessment, 'category'>) => void\n ) {\n const { deviceNamespaces } = document.deviceSigned\n\n // The check only applies when the mdoc actually authenticated device-signed elements.\n if (collectDeviceSignedElements(deviceNamespaces).length === 0) return\n\n const unauthorized = findUnauthorizedDeviceSignedElements({\n deviceNamespaces,\n keyAuthorizations: document.issuerSigned.issuerAuth.mobileSecurityObject.deviceKeyInfo.keyAuthorizations,\n })\n\n onCheck({\n status: unauthorized.length === 0 ? 'PASSED' : 'FAILED',\n check: 'Device signed elements must be authorized by the key authorizations in the mobile security object',\n reason: unauthorized.length ? describeUnauthorizedDeviceSignedElements(unauthorized) : undefined,\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import type { VerificationCallback } from '../mdoc/check-callback'\nimport type { DataElementIdentifier } from '../mdoc/models/data-element-identifier'\nimport type { DataElementValue } from '../mdoc/models/data-element-value'\nimport type { DeviceRequest } from '../mdoc/models/device-request'\nimport type { ItemsRequest } from '../mdoc/models/items-request'\nimport type { Namespace } from '../mdoc/models/namespace'\n\n/**\n * ISO/IEC 18013-5 7.2.5: `NN` is always two digits, from `00` to `99`.\n */\nconst ageOverIdentifierPattern = /^age_over_(\\d{2})$/\nconst maximumAgeOverRequests = 2\n\nexport type AgeOverCandidate = {\n elementIdentifier: DataElementIdentifier\n elementValue: DataElementValue\n}\n\n/**\n * The `NN` of an `age_over_NN` element identifier, or `undefined` when the identifier is not an\n * age attestation. `NN` must be exactly two digits, so `age_over_8`, `age_over_018` and\n * `age_over_18a` are not age attestations.\n */\nexport const parseAgeOverIdentifier = (elementIdentifier: DataElementIdentifier): number | undefined => {\n const match = ageOverIdentifierPattern.exec(elementIdentifier)\n return match ? Number(match[1]) : undefined\n}\n\n/**\n * Find the `age_over_MM` attestation that answers a request for `age_over_NN`.\n *\n * ISO/IEC 18013-5 7.2.5 lets the mdoc answer with a different age attestation than the one\n * requested: the nearest one that is `true` for `MM >= NN`, and otherwise the nearest one that is\n * `false` for `MM <= NN`.\n */\nexport const findAgeOverCandidate = <Candidate extends AgeOverCandidate>(\n requestedElementIdentifier: DataElementIdentifier,\n candidates: Array<Candidate>\n): Candidate | undefined => {\n const requestedNn = parseAgeOverIdentifier(requestedElementIdentifier)\n if (requestedNn === undefined) return undefined\n\n const ageOverCandidates = candidates.flatMap((candidate) => {\n const nn = parseAgeOverIdentifier(candidate.elementIdentifier)\n return nn === undefined ? [] : [{ nn, candidate }]\n })\n\n const nearestTrue = ageOverCandidates\n .filter(({ nn, candidate }) => candidate.elementValue === true && nn >= requestedNn)\n .sort((a, b) => a.nn - b.nn)[0]\n if (nearestTrue) return nearestTrue.candidate\n\n const nearestFalse = ageOverCandidates\n .filter(({ nn, candidate }) => candidate.elementValue === false && nn <= requestedNn)\n .sort((a, b) => b.nn - a.nn)[0]\n\n return nearestFalse?.candidate\n}\n\n/**\n * The namespaces with more than two distinct `age_over_NN` element identifiers, with those\n * identifiers.\n *\n * ISO/IEC 18013-5 7.2.5: \"an mDL reader shall not request more than two age_over_NN data elements\".\n * Counted per namespace, as an age attestation only answers requests in its own namespace.\n */\nexport const findAgeOverLimitViolations = (\n namespaces: Iterable<readonly [Namespace, Iterable<DataElementIdentifier>]>\n): Array<AgeOverLimitViolation> =>\n Array.from(namespaces, ([namespace, elementIdentifiers]) => ({\n namespace,\n ageOverIdentifiers: Array.from(new Set(elementIdentifiers)).filter(\n (elementIdentifier) => parseAgeOverIdentifier(elementIdentifier) !== undefined\n ),\n })).filter(({ ageOverIdentifiers }) => ageOverIdentifiers.length > maximumAgeOverRequests)\n\nexport type AgeOverLimitViolation = {\n namespace: Namespace\n ageOverIdentifiers: Array<DataElementIdentifier>\n}\n\n/**\n * {@link findAgeOverLimitViolations} for the namespaces of an `ItemsRequest`.\n */\nexport const findAgeOverRequestLimitViolations = (namespaces: ItemsRequest['namespaces']) =>\n findAgeOverLimitViolations(Array.from(namespaces, ([namespace, elements]) => [namespace, elements.keys()] as const))\n\n/**\n * E.g. `'age_over_18', 'age_over_21', 'age_over_65' in namespace 'org.iso.18013.5.1'`.\n */\nexport const describeAgeOverLimitViolations = (violations: Array<AgeOverLimitViolation>) =>\n violations\n .map(\n ({ namespace, ageOverIdentifiers }) =>\n `${ageOverIdentifiers.map((elementIdentifier) => `'${elementIdentifier}'`).join(', ')} in namespace '${namespace}'`\n )\n .join(' and ')\n\n/**\n * Report through `onCheck` whether every doc request of `deviceRequest` requests at most two\n * `age_over_NN` elements per namespace (18013-5 7.2.5).\n */\nexport const verifyAgeOverRequestLimit = (deviceRequest: DeviceRequest, onCheck: VerificationCallback) => {\n const reasons = deviceRequest.docRequests.flatMap((docRequest, docRequestIndex) => {\n const violations = findAgeOverRequestLimitViolations(docRequest.itemsRequest.namespaces)\n return violations.length === 0\n ? []\n : [`Doc request ${docRequestIndex} requests ${describeAgeOverLimitViolations(violations)}`]\n })\n\n onCheck({\n status: reasons.length === 0 ? 'PASSED' : 'FAILED',\n category: 'DOCUMENT_FORMAT',\n check: `Device request must not request more than ${maximumAgeOverRequests} age_over_NN elements per namespace`,\n reason: reasons.length === 0 ? undefined : reasons.join('; '),\n })\n}\n","import { typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { describeAgeOverLimitViolations, findAgeOverRequestLimitViolations } from '../../utils/ageOver'\nimport { AgeOverLimitExceededError } from '../errors'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\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 OriginalBytesCborStructure<\n ItemsRequestEncodedStructure,\n ItemsRequestDecodedStructure\n> {\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 /**\n * Throws an `AgeOverLimitExceededError` when more than two `age_over_NN` elements are requested in\n * a namespace (18013-5 7.2.5). A decoded items request is not checked, so that the mdoc can report\n * such a request instead.\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 violations = findAgeOverRequestLimitViolations(namespaces)\n if (violations.length > 0) {\n throw new AgeOverLimitExceededError(\n `Items request for docType '${options.docType}' requests ${describeAgeOverLimitViolations(violations)}, but at most two age_over_NN elements may be requested per namespace`\n )\n }\n\n const structure = new Map<unknown, unknown>([\n ['docType', options.docType],\n ['nameSpaces', namespaces],\n ])\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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.fromDataItem(itemsRequestDataItem),\n }),\n encode: ({ sessionTranscript, itemsRequest }) =>\n [\n 'ReaderAuthentication',\n sessionTranscript.encodedStructure,\n // `ItemsRequestBytes` are signed as the mdoc reader sent them (18013-5 8.1).\n itemsRequest.asDataItem,\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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). The chain in this Sign1's x5chain header is validated against\n * these anchors per RFC 5280. Without trust anchors the chain check FAILS,\n * unless `disableCertificateChainValidation` is set.\n */\n trustedCertificates?: Array<Uint8Array>\n /**\n * Only verify the detached signature, without establishing trust in the\n * reader's certificate chain. The reader is then not authenticated.\n */\n disableCertificateChainValidation?: boolean\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 let isValid: boolean\n let reason: string | undefined\n try {\n // `certificate` throws when the reader auth has no x5chain, which is required (18013-5 9.1.4).\n 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 reason = isValid ? undefined : 'Signature is invalid on the reader auth'\n } catch (error) {\n isValid = false\n reason = `Unable to verify the reader auth signature: ${error instanceof Error ? error.message : 'Unknown error'}`\n }\n\n onCheck({\n status: isValid ? 'PASSED' : 'FAILED',\n check: 'Reader auth signature must be valid',\n reason,\n })\n\n if (!options.disableCertificateChainValidation) {\n try {\n if (!options.trustedCertificates || 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 // biome-ignore lint/complexity/noThisInStatic: `super.create` keeps `this` bound to the subclass\n return super.create(options) as ReaderAuth\n }\n}\n","import { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { ItemsRequest } 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 map.set('itemsRequest', ItemsRequest.fromDataItem(input.get('itemsRequest')))\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 // `ItemsRequestBytes` are embedded as received, as reader authentication signs them.\n map.set('itemsRequest', output.get('itemsRequest').asDataItem)\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","/**\n * The value of an own property of `record`, so that a key such as `constructor` or `toString` does\n * not resolve to a property of `Object.prototype`. Namespaces and element identifiers come from the\n * device request, so they are used as keys as they are.\n */\nexport const getOwnProperty = <Value>(record: Record<string, Value> | undefined, key: string): Value | undefined =>\n // biome-ignore lint/suspicious/noPrototypeBuiltins: `Object.hasOwn` is not in the ES2020 lib this package targets\n record && Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined\n","import type { VerificationCallback } from '../mdoc/check-callback'\n\n/**\n * ISO/IEC 18013-5 8.1: a version is `major.minor`, and an unknown minor version of a known major\n * version must not cause an error. Every structure this library supports has major version 1.\n */\nexport const supportedVersionRegex = /^1\\.\\d+$/\n\nexport const isSupportedVersion = (version: string) => supportedVersionRegex.test(version)\n\n/**\n * Report through `onCheck` whether the version of a structure has a major version this library\n * supports.\n */\nexport const verifyVersion = (\n options: { structure: string; version: string | undefined },\n onCheck: VerificationCallback\n) => {\n const { structure, version } = options\n\n onCheck({\n status: version !== undefined && isSupportedVersion(version) ? 'PASSED' : 'FAILED',\n category: 'DOCUMENT_FORMAT',\n check: `${structure} must have a supported version`,\n reason:\n version !== undefined && isSupportedVersion(version)\n ? undefined\n : `${structure} has version '${version}', but only major version 1 is supported`,\n })\n}\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 { supportedVersionRegex } from '../../utils/version'\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 ['version', z.string().regex(supportedVersionRegex)],\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import {\n type CoseHeadersFor,\n extendCoseHeaderClaims,\n ProtectedHeaders,\n protectedHeadersSchema,\n RegisteredCwtHeaderClaimKey,\n} from '@owf/cose'\nimport z from 'zod'\n\n/** CWT media types used by the ISO/IEC 18013-5 revocation mechanisms. */\nexport enum MediaTypes {\n IdentifierListCwt = 'application/identifierlist+cwt',\n}\n\n// § 12.3.6.4: \"The value of the type claim shall be 'application/identifierlist+cwt'\".\n// `typ` is a COSE header parameter (RFC 9596, label 16), not a CWT claim — the same place\n// `@owf/token-status-list` writes it on a status list CWT. Required in the protected bucket\n// specifically: RFC 9596 forbids `typ` in the unprotected headers, so an unprotected copy is\n// not integrity protected, and `Cwt.typ` ignores it.\nconst identifierListCwtProtectedHeaderClaims = extendCoseHeaderClaims([\n [\n RegisteredCwtHeaderClaimKey.Typ,\n z.literal(MediaTypes.IdentifierListCwt, {\n error: `Typ (protected header 16) shall be '${MediaTypes.IdentifierListCwt}' (ISO 18013-5 § 12.3.6.4)`,\n }),\n ],\n] as const)\n\n/**\n * The protected COSE headers of an identifier list CWT (ISO/IEC 18013-5 second edition\n * § 12.3.6.4): the registered COSE header claims, with `typ` (16) required and narrowed to the\n * identifier list media type.\n *\n * `alg` and `x5chain` are already typed by the registered claims, so they are not redeclared.\n */\nexport class IdentifierListCwtProtectedHeaders extends ProtectedHeaders<\n CoseHeadersFor<typeof identifierListCwtProtectedHeaderClaims>\n> {\n public static override get encodingSchema() {\n return protectedHeadersSchema(identifierListCwtProtectedHeaderClaims)\n }\n\n /**\n * Leaf certificate and chain from the `x5chain` header (RFC 9360 label 33), normalized to an\n * array. § 12.3.6.3 requires it: \"The CWT shall contain the x5chain in the protected header\".\n */\n public get x5chain(): Array<Uint8Array> | undefined {\n const x5chain = this.headers.get(RegisteredCwtHeaderClaimKey.X5Chain)\n return x5chain instanceof Uint8Array ? [x5chain] : x5chain\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import {\n type CreateCwtPayloadOptions,\n CwtClaimVerificationError,\n CwtPayload,\n cwtPayloadClaimsFromOptions,\n extendCwtPayloadClaims,\n RegisteredCwtClaimKey,\n TypedMap,\n type VerifyCwtClaimsOptions,\n} from '@owf/cose'\nimport { StatusListCwtClaimKey } from '@owf/token-status-list'\nimport z from 'zod'\nimport { InvalidRevocationListError } from '../errors'\nimport { IdentifierList, type IdentifierListEncodedStructure } from './identifier-list'\n\n/**\n * CWT payload claim carrying the identifier list (ISO/IEC 18013-5 second edition § 12.3.6.4).\n * Mirrors `StatusListCwtClaimKey` from `@owf/token-status-list`.\n */\nexport enum IdentifierListCwtClaimKey {\n IdentifierList = 65530,\n}\n\n/**\n * The registered CWT claims, with the ones an identifier list CWT requires narrowed to\n * non-optional, plus the identifier list claim itself.\n */\nconst identifierListCwtPayloadSchema = extendCwtPayloadClaims(\n [\n // § 12.3.6.3 defers to the Token Status List specification, where `sub` and `iat` are\n // REQUIRED claims of a Status List Token. `sub` shall equal the `uri` of the\n // `IdentifierListInfo` that pointed here; that equality is checked by `verifyClaims`.\n [RegisteredCwtClaimKey.Subject, z.string()],\n [RegisteredCwtClaimKey.IssuedAt, z.number()],\n // § 12.3.6.3: \"The exp claim shall be present.\"\n [RegisteredCwtClaimKey.ExpirationTime, z.number()],\n [IdentifierListCwtClaimKey.IdentifierList, z.instanceof(IdentifierList)],\n // § 12.3.6.4: \"The StatusList claim shall not be present in the CWT claims set.\" Declared as\n // `never` rather than checked afterwards, so the two revocation mechanisms cannot be mixed in\n // one token and the claims set is rejected where every other claim is validated.\n [\n StatusListCwtClaimKey.StatusList,\n z\n .never({\n error: `The StatusList claim (${StatusListCwtClaimKey.StatusList}) shall not be present in an identifier list CWT (ISO 18013-5 § 12.3.6.4)`,\n })\n .exactOptional(),\n ],\n ] as const,\n { keyLabels: { ...IdentifierListCwtClaimKey, ...StatusListCwtClaimKey } }\n)\n\nexport type IdentifierListCwtPayloadEncodedStructure = z.input<typeof identifierListCwtPayloadSchema>\nexport type IdentifierListCwtPayloadDecodedStructure = z.infer<typeof identifierListCwtPayloadSchema>\n\nexport type CreateIdentifierListCwtPayloadOptions = Omit<CreateCwtPayloadOptions, 'subject' | 'expirationTime'> & {\n identifierList: IdentifierList\n\n /**\n * URI the list is published at. Becomes the `sub` claim, and shall equal the `uri` of the MSO's\n * `IdentifierListInfo`.\n */\n uri: string\n\n /** § 12.3.6.3: \"The exp claim shall be present.\" */\n expirationTime: Date\n}\n\n/**\n * The options {@link IdentifierListCwtPayload.verifyClaims} takes: the generic CWT ones, with `sub`\n * replaced by the `uri` it has to be equal to. Matches `VerifyStatusListCwtClaimsOptions`, so both\n * revocation mechanisms are verified through the same shape.\n */\nexport type VerifyIdentifierListCwtClaimsOptions = Omit<VerifyCwtClaimsOptions, 'expectedSubject' | 'keyLabels'> & {\n /** The `uri` of the `IdentifierListInfo` the token was fetched for, which `sub` must equal. */\n uri: string\n}\n\n/**\n * The claims set of an identifier list CWT (ISO/IEC 18013-5 second edition § 12.3.6.4).\n *\n * The registered claims — `sub`, `iat`, `exp` — come from {@link CwtPayload}, and narrow to\n * non-optional here because the schema above redeclares them as required.\n */\nexport class IdentifierListCwtPayload extends CwtPayload<IdentifierListCwtPayloadDecodedStructure> {\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 override create(options: CreateIdentifierListCwtPayloadOptions) {\n // `iat` is required for a status list token, so it defaults to now rather than being omitted.\n // NOTE: applied after the spread, so that an explicit `issuedAt: undefined` — what passing\n // through an optional value gives — defaults the same way omitting the key does.\n const claims = cwtPayloadClaimsFromOptions({\n ...options,\n subject: options.uri,\n issuedAt: options.issuedAt ?? new Date(),\n })\n\n claims.set(IdentifierListCwtClaimKey.IdentifierList, options.identifierList)\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(TypedMap.fromMap(claims))\n }\n\n /** `identifier_list` (65530) */\n public get identifierList(): IdentifierList {\n return this.getClaim(IdentifierListCwtClaimKey.IdentifierList)\n }\n\n /**\n * Verifies the claims of an identifier list token, on top of the generic CWT ones. § 12.3.6.1\n * makes the Token Status List verification requirements binding on both revocation mechanisms,\n * so `sub` and `iat` are REQUIRED and `sub` has to match the URI the token was referenced by —\n * without that check a list published for one URI can be replayed for another under the same\n * trust anchor. § 12.3.6.3 additionally requires `exp`.\n *\n * The counterpart of `StatusListCwtPayload.verifyClaims`, with the same defaults, including a\n * 30 second clock skew tolerance.\n *\n * @throws InvalidRevocationListError if a required claim is missing, `sub` is not the referenced\n * URI, or the token is outside its validity window.\n */\n public override verifyClaims({ uri, requiredClaims = [], ...options }: VerifyIdentifierListCwtClaimsOptions): void {\n try {\n super.verifyClaims({\n ...options,\n expectedSubject: uri,\n requiredClaims: [\n RegisteredCwtClaimKey.Subject,\n RegisteredCwtClaimKey.IssuedAt,\n RegisteredCwtClaimKey.ExpirationTime,\n ...requiredClaims,\n ],\n keyLabels: IdentifierListCwtClaimKey,\n })\n } catch (error) {\n if (error instanceof CwtClaimVerificationError) {\n throw new InvalidRevocationListError(`Identifier list token claim verification failed. ${error.message}`)\n }\n\n throw error\n }\n }\n}\n","import {\n type AnyCwt,\n Cwt,\n type CwtOptions,\n type CwtStaticThis,\n type CwtStructures,\n type CwtVerifyContext,\n type CwtVerifyOptions,\n ProtectedHeaders,\n RegisteredCwtHeaderClaimKey,\n TypedMap,\n type UnprotectedHeaderOptions,\n type UnprotectedHeaders,\n} from '@owf/cose'\nimport { hex, isMediaType } from '@owf/identity-common'\nimport type { MdocContext } from '../../context'\nimport { IdentifierFoundInRevokedListError, InvalidRevocationListError } from '../errors'\nimport { IdentifierListCwtProtectedHeaders, MediaTypes } from './identifier-list-cwt-headers'\nimport {\n type CreateIdentifierListCwtPayloadOptions,\n IdentifierListCwtClaimKey,\n IdentifierListCwtPayload,\n} from './identifier-list-cwt-payload'\n\nexport type IdentifierListCwtOptions = Omit<\n CwtOptions<IdentifierListCwtPayload, IdentifierListCwtProtectedHeaders>,\n 'payload' | 'protectedHeaders'\n> & {\n payload: IdentifierListCwtPayload | CreateIdentifierListCwtPayloadOptions\n\n /**\n * The protected headers. `typ` (16) is set to the identifier list media type when absent, so only\n * the one value it is allowed to have has to be supplied.\n */\n protectedHeaders?: IdentifierListCwtProtectedHeaders | ProtectedHeaders | Map<number, unknown>\n\n unprotectedHeaders?: UnprotectedHeaders | UnprotectedHeaderOptions['unprotectedHeaders']\n}\n\n/**\n * Builds the protected headers of an identifier list CWT, defaulting `typ` (16) to the identifier\n * list media type. Validated against {@link IdentifierListCwtProtectedHeaders}, so a `typ` that is\n * present but says the token is something else is rejected here rather than silently overwritten.\n */\nfunction identifierListProtectedHeaders(\n protectedHeaders: IdentifierListCwtOptions['protectedHeaders']\n): IdentifierListCwtProtectedHeaders {\n if (protectedHeaders instanceof IdentifierListCwtProtectedHeaders) return protectedHeaders\n\n const headers = new Map<number, unknown>(\n protectedHeaders instanceof ProtectedHeaders ? protectedHeaders.decodedStructure : protectedHeaders\n )\n if (headers.get(RegisteredCwtHeaderClaimKey.Typ) === undefined) {\n headers.set(RegisteredCwtHeaderClaimKey.Typ, MediaTypes.IdentifierListCwt)\n }\n\n return IdentifierListCwtProtectedHeaders.fromDecodedStructure(TypedMap.fromMap(headers))\n}\n\n/**\n * A revocation list token in CWT format that enumerates revoked MSO identifiers, rather than\n * indexing statuses by position (ISO/IEC 18013-5 second edition § 12.3.6.4). Presence of an\n * identifier means the MSO carrying it is revoked; absence means it is valid.\n *\n * The counterpart of `StatusListCwt` from `@owf/token-status-list`, and built the same way: the\n * claims set and protected headers validate themselves, and this class only names them and adds\n * what is specific to an identifier list.\n */\nexport class IdentifierListCwt extends Cwt<IdentifierListCwtPayload, IdentifierListCwtProtectedHeaders> {\n public constructor(options: IdentifierListCwtOptions) {\n super({\n ...options,\n protectedHeaders: identifierListProtectedHeaders(options.protectedHeaders),\n payload:\n options.payload instanceof IdentifierListCwtPayload\n ? options.payload\n : IdentifierListCwtPayload.create(options.payload),\n })\n }\n\n /**\n * Decodes an identifier list CWT from a tagged COSE_Sign1 (tag 18) or COSE_Mac0 (tag 17) token.\n *\n * @throws CwtPayloadDecodeError if the payload is not a valid identifier list claims set.\n * @throws ZodValidationError if the protected headers do not carry the identifier list `typ`.\n */\n public static override fromToken<T extends AnyCwt>(this: CwtStaticThis<T>, token: Uint8Array): T {\n // NOTE: `super.fromToken`, not `Cwt.fromToken`: the base implementation constructs `this`, so a\n // subclass of IdentifierListCwt is what comes back. The cast is because TypeScript resolves\n // `super.fromToken` against the base class, and cannot see that `T` is made of these structures.\n // biome-ignore lint/complexity/noThisInStatic: `super.fromToken` keeps `this` bound to the subclass\n return super.fromToken(token, {\n payload: IdentifierListCwtPayload,\n protectedHeaders: IdentifierListCwtProtectedHeaders,\n } as unknown as CwtStructures<T>) as T\n }\n\n /**\n * Fetches the identifier list published at `uri`.\n *\n * The counterpart of `fetchStatusList`, which the Token Status List specification's own media\n * type has; an identifier list is an ISO addition that `@owf/token-status-list` does not know\n * about, so the content type negotiation for it lives here.\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, { headers: { Accept: MediaTypes.IdentifierListCwt } })\n\n if (!response.ok) {\n throw new InvalidRevocationListError(`Identifier list fetch at ${uri} failed with status '${response.status}'`)\n }\n\n // Token Status List § 8.2, applied to the identifier list media type by § 12.3.6.4. A response\n // without a Content-Type is let through — the token itself carries the media type in `typ`, and\n // is rejected there if it is not an identifier list.\n const contentType = response.headers.get('Content-Type')\n if (contentType !== null && !isMediaType(contentType, MediaTypes.IdentifierListCwt)) {\n throw new InvalidRevocationListError(\n `Identifier list at ${uri} was served as '${contentType}', expected '${MediaTypes.IdentifierListCwt}'`\n )\n }\n\n return IdentifierListCwt.fromToken(new Uint8Array(await response.arrayBuffer()))\n }\n\n /** Leaf certificate and chain from the CWT's protected `x5chain` header, normalized to an array. */\n public get x5chain(): Array<Uint8Array> | undefined {\n return this.protectedHeaders.x5chain\n }\n\n /** True when `id` appears in the published list, and the MSO carrying it is therefore revoked. */\n public includes(id: Uint8Array): boolean {\n return this.payload.identifierList.includes(id)\n }\n\n /**\n * Verify the token completely: its signature or authentication tag, its claims, and — when `id`\n * is given — that the MSO carrying that identifier has not been revoked. The counterpart of\n * `StatusListCwt.verify`, which takes the `idx` into the status list where this takes the `id`\n * from the MSO's `IdentifierListInfo`.\n *\n * @throws CoseInvalidSignatureError if the signature or authentication tag does not verify.\n * @throws InvalidRevocationListError if the claims do not.\n * @throws IdentifierFoundInRevokedListError if `id` is on the list.\n */\n public override async verify(\n { id, ...options }: CwtVerifyOptions<IdentifierListCwtPayload> & { id?: Uint8Array },\n ctx: CwtVerifyContext\n ): Promise<void> {\n await super.verify(options, ctx)\n\n if (id !== undefined) this.verifyStatus(id)\n }\n\n /**\n * Verify that `id` is not on this list, without verifying the remaining claims or the signature.\n *\n * @throws IdentifierFoundInRevokedListError if it is, which per § 12.3.6.4 means the MSO carrying\n * it is revoked.\n */\n public verifyStatus(id: Uint8Array): void {\n if (this.includes(id)) {\n throw new IdentifierFoundInRevokedListError(\n `Identifier ${hex.encode(id)} found in the revoked identifier list at '${this.payload.subject}'`\n )\n }\n }\n}\n\nexport { IdentifierListCwtClaimKey }\n","import {\n CoseInvalidSignatureError,\n RegisteredCwtClaimKey,\n RegisteredCwtHeaderClaimKey,\n type SignatureAlgorithm,\n} from '@owf/cose'\nimport { fetchStatusList, SLException, StatusListCwt, type StatusListInfo } from '@owf/token-status-list'\nimport type { MdocContext } from '../../context'\nimport {\n InvalidIdentifierListSignatureError,\n InvalidRevocationListError,\n InvalidSignatureError,\n JwtNotSupportForStatusListError,\n type MdlError,\n NoPublicKeySetOnStatusListError,\n TrustedRevocationCertificatesMustContainAtleastOneCertificateError,\n UnableToExtractX5ChainFromCwtError,\n UnableToExtractX5ChainFromIdentifierListError,\n} from '../errors'\nimport { IdentifierListCwt } from './identifier-list-cwt'\nimport type { IdentifierListInfo } from './identifier-list-info'\n\n/**\n * Runs the claim and status checks `@owf/cose` and `@owf/token-status-list` own, translating the\n * errors they raise into the mdoc error hierarchy so that a caller of `IssuerAuth.verify` only ever\n * has to know `MdlError`.\n */\nasync function asMdlRevocationListError(\n verification: () => Promise<unknown> | unknown,\n /** The error to report a failed signature as. */\n invalidSignatureError: new (message: string) => MdlError\n): Promise<void> {\n try {\n await verification()\n } catch (error) {\n if (error instanceof CoseInvalidSignatureError) throw new invalidSignatureError(error.message)\n if (error instanceof SLException) throw new InvalidRevocationListError(error.message)\n throw error\n }\n}\n\n/**\n * The trust anchors a revocation list signer is validated against. Also checked before the list is\n * fetched, so that a verification that cannot succeed does not request the URI in the MSO.\n */\nfunction assertTrustedCertificates({\n trustedCertificates,\n}: {\n trustedCertificates?: Array<Uint8Array>\n}): Array<Uint8Array> {\n if (!trustedCertificates || trustedCertificates.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 return trustedCertificates\n}\n\n/**\n * Establishes the signer of a revocation list: the certificate chain it carries, validated against\n * the mdoc trust anchors unless certificate chain validation is disabled, and the public key of its\n * leaf.\n *\n * § 12.3.6.3 requires the chain to travel in the protected header of the CWT: \"The CWT shall\n * contain the x5chain in the protected header that contains the certificate or chain of\n * certificates used to verify the signature\".\n */\nasync function verifyRevocationListSigner(\n {\n x5chain,\n algorithm,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n }: {\n x5chain: Array<Uint8Array>\n algorithm?: SignatureAlgorithm\n trustedCertificates?: Array<Uint8Array>\n disableCertificateChainValidation?: boolean\n now: Date\n },\n ctx: Pick<MdocContext, 'x509'>\n) {\n let chain: Array<Uint8Array> | undefined\n if (!disableCertificateChainValidation) {\n ;({ chain } = await ctx.x509.verifyCertificateChain({\n trustedCertificates: assertTrustedCertificates({ trustedCertificates }),\n x5chain,\n now,\n }))\n }\n\n const key = await ctx.x509.getPublicKey({ certificate: x5chain[0], algorithm })\n if (!key) {\n throw new NoPublicKeySetOnStatusListError()\n }\n\n return { chain, key }\n}\n\nexport type VerifyStatusListTokenOptions = {\n statusListInfo: Pick<StatusListInfo, 'uri' | 'idx'>\n /**\n * Trust anchors for the certificate chain of the list signer. Required unless\n * `disableCertificateChainValidation` is set.\n */\n trustedCertificates?: Array<Uint8Array>\n /**\n * Verify the list with the key of the leaf of its x5chain, without validating the chain.\n */\n disableCertificateChainValidation?: boolean\n now?: Date\n skewSeconds?: number\n checkFreshness?: boolean\n}\n\nexport type VerifyStatusListTokenResult = {\n statusListCwt: StatusListCwt\n /** The validated certificate chain of the list signer, leaf first. Not set without chain validation. */\n chain?: Array<Uint8Array>\n}\n\n/**\n * Fetch and verify the status list a `StatusListInfo` points at.\n *\n * `@owf/token-status-list` owns everything status-list-shaped — fetching and content-type\n * negotiation, the CWT structure, the claim checks and reading a status by index. What lives here\n * is only what that library cannot know about: the mdoc trust anchors and the `MdocContext` crypto\n * callbacks used to establish the signer, and the two rules ISO/IEC 18013-5 § 12.3.6 layers on top\n * of the Token Status List defaults — a mandatory `exp` (§ 12.3.6.3), and `Valid` as the only\n * acceptable status, since § 12.3.6.1 allows \"no other status besides 'revoked'\".\n *\n * § 12.3.6.3 requires the list to be a Status List Token \"in CWT format, since the IssuerAuth\n * structure is a CWT\", so a list served as a JWT is rejected rather than verified.\n */\nexport async function verifyStatusListToken(\n {\n statusListInfo,\n trustedCertificates,\n disableCertificateChainValidation,\n now = new Date(),\n skewSeconds,\n checkFreshness,\n }: VerifyStatusListTokenOptions,\n ctx: Pick<MdocContext, 'fetch' | 'x509' | 'cose'>\n): Promise<VerifyStatusListTokenResult> {\n if (!disableCertificateChainValidation) assertTrustedCertificates({ trustedCertificates })\n\n const { uri, idx } = statusListInfo\n const token = await fetchStatusList({ uri, customFetcher: ctx.fetch, acceptedFormats: ['cwt'] })\n\n // `fetchStatusList` decides on the response's Content-Type, not on `acceptedFormats`, so a JWT\n // still comes back as a string even though it was not asked for.\n if (typeof token === 'string') {\n throw new JwtNotSupportForStatusListError(\n `The status list at ${uri} was served in JWT format. ISO/IEC 18013-5 § 12.3.6.3 requires a Status List Token in CWT format, which is the only format @owf/mdoc verifies`\n )\n }\n\n const statusListCwt = StatusListCwt.fromToken(token)\n\n const x5chain = normalizeX5Chain(statusListCwt.protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.X5Chain))\n if (!x5chain) {\n throw new UnableToExtractX5ChainFromCwtError()\n }\n\n const { chain, key } = await verifyRevocationListSigner(\n {\n x5chain,\n algorithm: statusListCwt.algorithm as SignatureAlgorithm | undefined,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n },\n ctx\n )\n\n // Signature, claims and the status at `idx`, in one call: the token is only the issuer's if it\n // verifies, so there is nothing to read from it before that.\n await asMdlRevocationListError(\n () =>\n statusListCwt.verify(\n {\n key,\n uri,\n idx,\n now,\n skewSeconds,\n checkIssuedAt: checkFreshness,\n // § 12.3.6.3: \"The exp claim shall be present.\" OPTIONAL in the Token Status List\n // specification, which is why it is required here rather than there.\n requiredClaims: [RegisteredCwtClaimKey.ExpirationTime],\n },\n { sign1: ctx.cose.sign1 }\n ),\n InvalidSignatureError\n )\n\n return { statusListCwt, chain }\n}\n\nexport type VerifyIdentifierListTokenOptions = {\n identifierListInfo: Pick<IdentifierListInfo, 'uri' | 'id'>\n /**\n * Trust anchors for the certificate chain of the list signer. Required unless\n * `disableCertificateChainValidation` is set.\n */\n trustedCertificates?: Array<Uint8Array>\n /**\n * Verify the list with the key of the leaf of its x5chain, without validating the chain.\n */\n disableCertificateChainValidation?: boolean\n now?: Date\n skewSeconds?: number\n checkFreshness?: boolean\n}\n\nexport type VerifyIdentifierListTokenResult = {\n identifierListCwt: IdentifierListCwt\n /** The validated certificate chain of the list signer, leaf first. Not set without chain validation. */\n chain?: Array<Uint8Array>\n}\n\n/**\n * Fetch and verify the identifier list an `IdentifierListInfo` points at (§ 12.3.6.4):\n * certificate chain, signature, the claim checks § 12.3.6.1 makes binding on both revocation\n * mechanisms, and finally whether the MSO's own identifier appears in it — presence means revoked.\n *\n * The counterpart of {@link verifyStatusListToken}. Unlike a status list, the identifier list is an\n * ISO addition that the Token Status List specification does not describe, so `IdentifierListCwt`\n * lives in this package rather than in `@owf/token-status-list` — built on the same `Cwt`, so the\n * two are verified the same way.\n */\nexport async function verifyIdentifierListToken(\n {\n identifierListInfo,\n trustedCertificates,\n disableCertificateChainValidation,\n now = new Date(),\n skewSeconds,\n checkFreshness,\n }: VerifyIdentifierListTokenOptions,\n ctx: Pick<MdocContext, 'fetch' | 'x509' | 'cose'>\n): Promise<VerifyIdentifierListTokenResult> {\n if (!disableCertificateChainValidation) assertTrustedCertificates({ trustedCertificates })\n\n const { uri, id } = identifierListInfo\n const identifierListCwt = await IdentifierListCwt.fetch(uri, ctx)\n\n const x5chain = identifierListCwt.x5chain\n if (!x5chain || x5chain.length === 0) {\n throw new UnableToExtractX5ChainFromIdentifierListError()\n }\n\n const { chain, key } = await verifyRevocationListSigner(\n {\n x5chain,\n algorithm: identifierListCwt.algorithm as SignatureAlgorithm | undefined,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n },\n ctx\n )\n\n await asMdlRevocationListError(\n () =>\n identifierListCwt.verify(\n { key, uri, id, now, skewSeconds, checkIssuedAt: checkFreshness },\n { sign1: ctx.cose.sign1 }\n ),\n InvalidIdentifierListSignatureError\n )\n\n return { identifierListCwt, chain }\n}\n\n/** COSE_X509 carries either a single certificate or a chain of them (RFC 9360). */\nfunction normalizeX5Chain(x5chain: unknown): Array<Uint8Array> | undefined {\n const chain = x5chain instanceof Uint8Array ? [x5chain] : x5chain\n if (!Array.isArray(chain) || chain.length === 0 || !chain.every((c) => c instanceof Uint8Array)) return undefined\n return chain\n}\n","import {\n CosePayloadMustBeDefinedError,\n cborDecode,\n DataItem,\n Sign1,\n type Sign1EncodedStructure,\n type Sign1Options,\n zUint8Array,\n} from '@owf/cose'\nimport { compareBytes } from '@owf/identity-common'\nimport type { 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 type { IdentifierListCwt } from './identifier-list-cwt'\nimport { MobileSecurityObject, type MobileSecurityObjectEncodedStructure } from './mobile-security-object.js'\nimport { verifyIdentifierListToken, verifyStatusListToken } from './mso-revocation-list'\n\nexport type IssuerAuthEncodedStructure = Sign1EncodedStructure\nexport type IssuerAuthOptions = Omit<Sign1Options, 'payload'> & {\n payload?: Sign1Options['payload'] | MobileSecurityObject\n}\n\nexport type IssuerAuthVerificationResult = {\n /**\n * The certificate chain of the document signer up to a trusted certificate. Undefined when\n * certificate chain validation is disabled, or when it failed and the verification callback did not throw.\n */\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 // biome-ignore lint/complexity/noThisInStatic: `super.create` keeps `this` bound to the subclass\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 /**\n * The `countryName` in the subject of the document signer certificate, which `issuing_country` must\n * match (18013-5 7.2.1).\n */\n public getIssuingCountry(ctx: Pick<MdocContext, 'x509'>) {\n return ctx.x509.getSubjectNameField({ certificate: this.certificate, field: 'C' })[0]\n }\n\n /**\n * The `stateOrProvinceName` in the subject of the document signer certificate, if present, which\n * `issuing_jurisdiction` must match (18013-5 7.2.1).\n */\n public getIssuingStateOrProvince(ctx: Pick<MdocContext, 'x509'>) {\n return ctx.x509.getSubjectNameField({ certificate: this.certificate, field: 'ST' })[0]\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 skewSeconds,\n checkFreshness,\n trustedStatusCertificates,\n disableCertificateChainValidation,\n }: {\n now?: Date\n /** Tolerance applied to the `exp` and `iat` of a revocation list. Defaults to 30 seconds. */\n skewSeconds?: number\n checkFreshness?: boolean\n trustedStatusCertificates?: Uint8Array[]\n /**\n * Verify a revocation list with the key of the leaf of its x5chain, without validating its\n * certificate chain against `trustedStatusCertificates`. The revocation status is still checked.\n */\n disableCertificateChainValidation?: boolean\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 const statusListResult = status.statusList\n ? await verifyStatusListToken(\n {\n statusListInfo: status.statusList,\n trustedCertificates: trustedStatusCertificates,\n disableCertificateChainValidation,\n now,\n skewSeconds,\n checkFreshness,\n },\n ctx\n )\n : undefined\n\n const identifierListResult = status.identifierList\n ? await verifyIdentifierListToken(\n {\n identifierListInfo: status.identifierList,\n trustedCertificates: trustedStatusCertificates,\n disableCertificateChainValidation,\n now,\n skewSeconds,\n checkFreshness,\n },\n ctx\n )\n : undefined\n\n return {\n statusList: statusListResult?.statusListCwt,\n trustedStatusListChain: statusListResult?.chain,\n identifierList: identifierListResult?.identifierListCwt,\n trustedIdentifierListChain: identifierListResult?.chain,\n }\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 // Status information is trusted when it is signed by a status certificate of the trust anchor\n // the issuance chain ends in.\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 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 let statusList: StatusListCwt | undefined\n let trustedStatusListChain: Uint8Array[] | undefined\n let identifierList: IdentifierListCwt | undefined\n let trustedIdentifierListChain: Uint8Array[] | undefined\n // The revocation list URIs come from the MSO, so they are only fetched once the MSO is known to be\n // signed by the issuer. A forged MSO must not make the verifier request a URI of its choosing.\n if (!disableStatusValidation && isSignatureValid) {\n try {\n ;({ statusList, trustedStatusListChain, identifierList, trustedIdentifierListChain } = await this.verifyStatus(\n {\n now,\n skewSeconds,\n checkFreshness: true,\n trustedStatusCertificates,\n // Without chain validation there is no trust anchor to take the status certificates from,\n // so the chains of the revocation lists are not validated either.\n disableCertificateChainValidation,\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 { 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()}); its validity period is ${validityInfo.validFrom.toUTCString()} to ${validityInfo.validUntil.toUTCString()} (allowed clock skew ${skewSeconds}s)`,\n })\n\n if (!disableCertificateChainValidation) {\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\n return {\n trustedIssuanceChain,\n statusList,\n trustedStatusListChain,\n identifierList,\n trustedIdentifierListChain,\n }\n }\n}\n","import { typedMap, zUint8Array } from '@owf/cose'\nimport { compareBytes } from '@owf/identity-common'\nimport { z } from 'zod'\nimport type { MdocContext } from '../../context'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\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\n/**\n * Decoded items keep the `IssuerSignedItemBytes` they were received as, as the digests in the MSO are\n * computed over them.\n */\nexport class IssuerSignedItem extends OriginalBytesCborStructure<\n IssuerSignedItemEncodedStructure,\n IssuerSignedItemDecodedStructure\n> {\n public static override get encodingSchema() {\n return issuerSignedItemSchema\n }\n\n /**\n * @deprecated Use {@link originalBytes}.\n */\n public get originalPayloadBytes() {\n return this.originalBytes\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 // 18013-5 7.2.1: the check \"is only required if the stateOrProvinceName element is present in the DS\n // certificate\".\n if (this.elementIdentifier === 'issuing_jurisdiction') {\n const stateOrProvince = issuerAuth.getIssuingStateOrProvince(ctx)\n return stateOrProvince === undefined || this.elementValue === stateOrProvince\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\n return this.fromEncodedStructure(map)\n }\n}\n","import { CborStructure, DataItem } from '@owf/cose'\nimport z from 'zod'\nimport { IssuerSignedItem } 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.fromDataItem(isi))\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 // Forward the issuer's own bytes for items we received rather than built. A\n // verifier digests the IssuerSignedItemBytes it is given and compares that to\n // valueDigests, so re-encoding from the decoded structure breaks the digest for\n // any issuer whose encoder differs from ours.\n value.map((isi) => isi.asDataItem)\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(options.issuerNamespaces)\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\n// 18013-5 8.3.2.1.2.2: `nameSpaces` is optional, and left out when no issuer-signed element is\n// disclosed, as `IssuerNameSpaces` must have at least one namespace.\nconst issuerSignedSchema = typedMap([\n ['nameSpaces', z.instanceof(IssuerNamespaces).exactOptional()],\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 if (input.has('nameSpaces')) {\n map.set(\n 'nameSpaces',\n IssuerNamespaces.fromEncodedStructure(input.get('nameSpaces') as IssuerNamespacesEncodedStructure)\n )\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 const nameSpaces = output.get('nameSpaces')\n if (nameSpaces !== undefined) map.set('nameSpaces', 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 Object.fromEntries(issuerSignedItems.map((item) => [item.elementIdentifier, item.elementValue]))\n }\n\n public get encodedForOid4Vci() {\n return base64url.encode(this.encode())\n }\n\n public static fromEncodedForOid4Vci(encoded: string): IssuerSigned {\n // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\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 // 18013-5 8.3.2.1.2.2: the mdoc shall not include two or more IssuerSignedItem elements with\n // the same element identifier in a single namespace and document.\n const elementIdentifiers = nsItems.map((item) => item.elementIdentifier)\n const duplicates = new Set(elementIdentifiers.filter((id, index) => elementIdentifiers.indexOf(id) !== index))\n onCheck({\n status: duplicates.size === 0 ? 'PASSED' : 'FAILED',\n check: `Namespace ${ns} must not include multiple elements with the same element identifier`,\n reason: duplicates.size\n ? `Namespace ${ns} includes multiple elements for ${Array.from(duplicates)\n .map((id) => `'${id}'`)\n .join(', ')}`\n : undefined,\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import type { VerificationCallback } from '../mdoc/check-callback'\nimport { InvalidDeviceRequestMatchOptionsError } from '../mdoc/errors'\nimport type { DataElementIdentifier } from '../mdoc/models/data-element-identifier'\nimport type { DataElementValue } from '../mdoc/models/data-element-value'\nimport type { DeviceNamespaces } from '../mdoc/models/device-namespaces'\nimport type { DeviceRequest } from '../mdoc/models/device-request'\nimport type { DeviceResponse } from '../mdoc/models/device-response'\nimport type { DocType } from '../mdoc/models/doctype'\nimport type { IntentToRetain } from '../mdoc/models/intent-to-retain'\nimport { IssuerSigned } from '../mdoc/models/issuer-signed'\nimport type { IssuerSignedItem } from '../mdoc/models/issuer-signed-item'\nimport type { KeyAuthorizations } from '../mdoc/models/key-authorizations'\nimport type { Namespace } from '../mdoc/models/namespace'\nimport { describeAgeOverLimitViolations, findAgeOverCandidate, findAgeOverRequestLimitViolations } from './ageOver'\nimport { getOwnProperty } from './getOwnProperty'\nimport { isDeviceSignedElementAuthorized } from './keyAuthorizations'\n\nexport type DisclosedElementSource = 'issuerSigned' | 'deviceSigned'\n\nexport type DisclosedElement = {\n namespace: Namespace\n elementIdentifier: DataElementIdentifier\n elementValue: DataElementValue\n source: DisclosedElementSource\n}\n\n/**\n * How a single requested element is matched. An `ItemsRequest` can express neither that an element\n * is optional nor where it is expected to come from, so the verifier — which built the request —\n * provides it as context to the match.\n */\nexport type ElementMatchOptions = {\n /**\n * Whether the response may leave this element out without failing the match. An optional element\n * never makes a document fail, but it is still reported per claim. Defaults to `false`.\n */\n optional?: boolean\n\n /**\n * Where the element may be disclosed from. Device-signed elements are asserted by the mdoc\n * itself and not by the issuer, so an element the issuer is expected to attest to, an\n * `age_over_NN` for instance, must not be answered from `deviceSigned`. Defaults to\n * `'issuerSigned'`.\n *\n * Even if `'deviceSigned'` is allowed, the element must be in the key authorizations of the mdoc.\n */\n source?: DisclosedElementSource | 'any'\n}\n\nexport type DocRequestMatchOptions = {\n /**\n * Index into `deviceRequest.docRequests` of the doc request these options apply to.\n */\n docRequestIndex: number\n\n /**\n * Per-element match options, keyed by namespace and element identifier. The element identifier\n * `'*'` applies to every element in the namespace that is not named explicitly, which is how a\n * namespace that is entirely device-signed is described.\n *\n * ```ts\n * {\n * 'org.iso.18013.5.1': { portrait: { optional: true } },\n * 'com.example.device': { '*': { source: 'deviceSigned' } },\n * }\n * ```\n */\n elements?: Record<Namespace, Record<DataElementIdentifier, ElementMatchOptions>>\n}\n\n/**\n * Per doc request the elements that are optional or that may be answered from `deviceSigned`. By\n * default every requested element is required and must be issuer-signed.\n */\nexport type DeviceRequestMatchOptions = {\n /**\n * A doc request can have options at most once.\n */\n docRequests?: Array<DocRequestMatchOptions>\n\n /**\n * A device request with more than one doc request does not say whether it asks for all of them, or\n * for any one of them. By default every doc request has to be satisfied. Set this to treat them as\n * alternatives instead, of which at least one has to be satisfied, which is a common\n * interpretation. The second edition of 18013-5 resolves the ambiguity with use cases in\n * `DeviceRequestInfo`, which are not supported yet.\n *\n * Does not apply to a device request with a single doc request. Defaults to `false`.\n */\n treatAmbiguousMultipleDocRequestsAsAlternatives?: boolean\n}\n\nexport type ClaimMatchBase = {\n namespace: Namespace\n /**\n * The element identifier as it appears in the `ItemsRequest`.\n */\n elementIdentifier: DataElementIdentifier\n intentToRetain: IntentToRetain\n /**\n * Whether the element was matched as optional, and therefore cannot make the claims fail. Always\n * `false` when matching the credentials of a holder, as the request does not say which elements\n * are optional.\n */\n optional: boolean\n}\n\nexport type ClaimMatchSuccess = ClaimMatchBase & {\n success: true\n /**\n * The element identifier that is disclosed. Only differs from `elementIdentifier` when an\n * `age_over_NN` request is answered with a different age attestation (18013-5 7.2.5).\n */\n disclosedElementIdentifier: DataElementIdentifier\n elementValue: DataElementValue\n source: DisclosedElementSource\n}\n\nexport type ClaimMatchFailure = ClaimMatchBase & {\n success: false\n /**\n * `'notDisclosed'` — the document did not disclose the element, or the credential cannot: the\n * issuer did not sign it, and either the device key is not authorized for it or no value was\n * provided for it in the device namespaces.\n *\n * `'disallowedSource'` — the document did disclose it, but only from a source the match options\n * do not allow for this element. By default only `issuerSigned` is allowed, so a `deviceSigned`\n * element the verifier did not mark as device-signed fails here rather than counting as a match.\n *\n * `'deviceKeyNotAuthorized'` — the document did disclose it device-signed, from a source the match\n * options allow, but the device key is not authorized for it in the key authorizations of the MSO\n * (18013-5 9.1.3.4).\n */\n failure: 'notDisclosed' | 'disallowedSource' | 'deviceKeyNotAuthorized'\n /**\n * The source the element was disclosed from, when `failure` is `'disallowedSource'` or\n * `'deviceKeyNotAuthorized'`.\n */\n disclosedFrom?: DisclosedElementSource\n reason: string\n}\n\nexport type ClaimMatch = ClaimMatchSuccess | ClaimMatchFailure\n\ntype NonEmptyArray<T> = [T, ...Array<T>]\n\nexport type DocTypeMatchSuccess = {\n success: true\n docType: DocType\n}\n\nexport type DocTypeMatchFailure = {\n success: false\n /**\n * The docType of the document or credential.\n */\n docType: DocType\n reason: string\n}\n\n/**\n * Whether a document or credential has the docType the doc request asks for.\n */\nexport type DocTypeMatchResult = DocTypeMatchSuccess | DocTypeMatchFailure\n\n/**\n * Every requested element that is not optional is disclosed.\n */\nexport type ClaimsMatchSuccess = {\n success: true\n /**\n * The requested elements that are disclosed, in request order.\n */\n validClaims: Array<ClaimMatchSuccess>\n /**\n * The optional requested elements that are not disclosed, in request order.\n */\n failedClaims: Array<ClaimMatchFailure & { optional: true }>\n}\n\n/**\n * At least one requested element that is not optional is not disclosed.\n */\nexport type ClaimsMatchFailure = {\n success: false\n /**\n * The requested elements that are disclosed, in request order.\n */\n validClaims: Array<ClaimMatchSuccess>\n /**\n * The requested elements that are not disclosed, in request order. Can contain optional elements.\n */\n failedClaims: NonEmptyArray<ClaimMatchFailure>\n}\n\nexport type ClaimsMatchResult = ClaimsMatchSuccess | ClaimsMatchFailure\n\ntype UnrequestedClaims = {\n /**\n * Elements the document disclosed that the doc request did not ask for. Not a failure by itself\n * — it is the mdoc over-disclosing — but a verifier should not process data it did not request.\n */\n unrequestedClaims: Array<DisclosedElement>\n}\n\nexport type DocumentClaimsMatchSuccess = ClaimsMatchSuccess & UnrequestedClaims\nexport type DocumentClaimsMatchFailure = ClaimsMatchFailure & UnrequestedClaims\nexport type DocumentClaimsMatchResult = DocumentClaimsMatchSuccess | DocumentClaimsMatchFailure\n\ntype DocumentMatchBase = {\n /**\n * Index into `deviceResponse.documents` of the document this result is about.\n */\n documentIndex: number\n}\n\nexport type DocumentMatchSuccess = DocumentMatchBase & {\n success: true\n docType: DocTypeMatchSuccess\n claims: DocumentClaimsMatchSuccess\n}\n\nexport type DocumentMatchFailure = DocumentMatchBase & {\n success: false\n docType: DocTypeMatchResult\n claims: DocumentClaimsMatchResult\n}\n\n/**\n * Whether a document satisfies a doc request. The `docType` check requires both the docType of the\n * document and the docType of its mobile security object to be the requested docType: the docType\n * outside the MSO is not signed.\n */\nexport type DocumentMatch = DocumentMatchSuccess | DocumentMatchFailure\n\ntype DocRequestMatchBase = {\n /**\n * Index into `deviceRequest.docRequests` of the doc request this result is about.\n */\n docRequestIndex: number\n docType: DocType\n /**\n * The documents that do not satisfy this doc request, in response order. This includes every\n * document of another docType, for which the `docType` check failed.\n */\n failedDocuments: Array<DocumentMatchFailure>\n}\n\nexport type DocRequestMatchSuccess = DocRequestMatchBase & {\n success: true\n /**\n * The documents that satisfy this doc request, in response order.\n */\n validDocuments: NonEmptyArray<DocumentMatchSuccess>\n}\n\nexport type DocRequestMatchFailure = DocRequestMatchBase & {\n success: false\n validDocuments: []\n}\n\nexport type DocRequestMatch = DocRequestMatchSuccess | DocRequestMatchFailure\n\ntype DocRequestsAsAlternatives = {\n /**\n * Whether the doc requests were matched as alternatives, of which at least one has to be\n * satisfied, rather than all of them. Only `true` when\n * `treatAmbiguousMultipleDocRequestsAsAlternatives` is set and the device request has more than\n * one doc request.\n */\n docRequestsAsAlternatives: boolean\n}\n\ntype DeviceRequestMatchBase = DocRequestsAsAlternatives & {\n /**\n * Documents in the response whose docType no doc request asked for.\n */\n unrequestedDocuments: Array<{ documentIndex: number; docType: DocType }>\n}\n\n/**\n * Every doc request is satisfied or, when matched as alternatives, at least one of them.\n */\nexport type DeviceRequestMatchSuccess = DeviceRequestMatchBase &\n (\n | {\n success: true\n docRequestsAsAlternatives: false\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<DocRequestMatchSuccess>\n }\n | {\n success: true\n docRequestsAsAlternatives: true\n /**\n * One entry per doc request, in request order. At least one is successful.\n */\n docRequests: Array<DocRequestMatch>\n }\n )\n\nexport type DeviceRequestMatchFailure = DeviceRequestMatchBase & {\n success: false\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<DocRequestMatch>\n}\n\nexport type DeviceRequestMatchResult = DeviceRequestMatchSuccess | DeviceRequestMatchFailure\n\ntype CredentialMatchBase = {\n /**\n * Index into `credentials` of the credential this result is about.\n */\n credentialIndex: number\n}\n\nexport type CredentialMatchSuccess = CredentialMatchBase & {\n success: true\n docType: DocTypeMatchSuccess\n claims: ClaimsMatchSuccess\n}\n\nexport type CredentialMatchFailure = CredentialMatchBase & {\n success: false\n docType: DocTypeMatchResult\n claims: ClaimsMatchResult\n}\n\n/**\n * Whether a credential can satisfy a doc request. The `docType` check requires the docType of the\n * mobile security object of the credential to be the requested docType.\n */\nexport type CredentialMatch = CredentialMatchSuccess | CredentialMatchFailure\n\ntype HolderDocRequestMatchBase = {\n /**\n * Index into `deviceRequest.docRequests` of the doc request this result is about.\n */\n docRequestIndex: number\n docType: DocType\n /**\n * The credentials that do not satisfy this doc request, in the order they were provided. This\n * includes every credential of another docType, for which the `docType` check failed. Empty when\n * the doc request is invalid, as credentials are then not matched.\n */\n failedCredentials: Array<CredentialMatchFailure>\n}\n\nexport type HolderDocRequestMatchSuccess = HolderDocRequestMatchBase & {\n success: true\n /**\n * The credentials that satisfy this doc request, in the order they were provided.\n */\n validCredentials: NonEmptyArray<CredentialMatchSuccess>\n}\n\n/**\n * Why a doc request cannot be answered by any credential.\n *\n * `'ageOverLimitExceeded'` — the doc request asks for more than two `age_over_NN` elements in a\n * namespace, which 18013-5 7.2.5 forbids a reader to do, as together they narrow down the age of\n * the holder.\n */\nexport type InvalidDocRequest = {\n failure: 'ageOverLimitExceeded'\n reason: string\n}\n\nexport type HolderDocRequestMatchFailure = HolderDocRequestMatchBase & {\n success: false\n validCredentials: []\n /**\n * Set when the doc request itself is invalid. No credential is then matched against it, so\n * `failedCredentials` is empty.\n */\n invalidDocRequest?: InvalidDocRequest\n}\n\nexport type HolderDocRequestMatch = HolderDocRequestMatchSuccess | HolderDocRequestMatchFailure\n\n/**\n * Every doc request can be answered or, when matched as alternatives, at least one of them.\n */\nexport type HolderDeviceRequestMatchSuccess =\n | {\n success: true\n docRequestsAsAlternatives: false\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<HolderDocRequestMatchSuccess>\n }\n | {\n success: true\n docRequestsAsAlternatives: true\n /**\n * One entry per doc request, in request order. At least one is successful.\n */\n docRequests: Array<HolderDocRequestMatch>\n }\n\nexport type HolderDeviceRequestMatchFailure = DocRequestsAsAlternatives & {\n success: false\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<HolderDocRequestMatch>\n}\n\nexport type HolderDeviceRequestMatchResult = HolderDeviceRequestMatchSuccess | HolderDeviceRequestMatchFailure\n\n/**\n * A credential of the holder, with the values the holder can disclose device-signed for it.\n */\nexport type HolderCredential = {\n issuerSigned: IssuerSigned\n /**\n * The values the holder can disclose device-signed with this credential. A requested element the\n * issuer did not sign only matches when its value is here and the device key is authorized for\n * it, the same as when creating the response.\n */\n deviceNamespaces?: DeviceNamespaces\n}\n\n/**\n * Match a `DeviceResponse` against the `DeviceRequest` it answers (verifier side).\n *\n * The ISO mdoc DC API protocol (`org-iso-mdoc`) has no query language such as DCQL that describes\n * which claims a response has to contain, so this walks the device request itself and reports, per\n * doc request, per document and per check whether the response satisfies it.\n *\n * An element only counts as disclosed when it comes from `issuerSigned`, as `deviceSigned` elements\n * are asserted by the mdoc itself rather than by the issuer. Pass `matchOptions` to mark elements\n * that are optional or that are expected to be device-signed.\n *\n * By default the match only succeeds when every doc request is satisfied. Set\n * `treatAmbiguousMultipleDocRequestsAsAlternatives` in `matchOptions` to have it succeed when at\n * least one is.\n *\n * Shares its matching with {@link matchCredentialsToDeviceRequest}, which matches like a verifier\n * that accepts every element from `'any'` source.\n *\n * This is purely a structural comparison — it does not verify issuer auth, device auth or the\n * digests of the disclosed elements. Use it alongside `DeviceResponse.verify`, which runs it as\n * part of verification when a `deviceRequest` is passed.\n */\nexport const matchDeviceRequest = (options: {\n deviceRequest: DeviceRequest\n deviceResponse: DeviceResponse\n matchOptions?: DeviceRequestMatchOptions\n}): DeviceRequestMatchResult => {\n const { deviceRequest, deviceResponse, matchOptions } = options\n const docRequestOptions = indexDocRequestOptions(deviceRequest, matchOptions)\n\n // Every access to the mobile security object decodes it, so decode it once per document.\n const documents = (deviceResponse.documents ?? []).map((document) => ({\n document,\n mobileSecurityObject: document.issuerSigned.issuerAuth.mobileSecurityObject,\n }))\n\n const docRequests = deviceRequest.docRequests.map((docRequest, docRequestIndex): DocRequestMatch => {\n const { docType, namespaces } = docRequest.itemsRequest\n const elements = docRequestOptions.get(docRequestIndex)?.elements\n\n const documentMatches = documents.map(({ document, mobileSecurityObject }, documentIndex): DocumentMatch => {\n const mobileSecurityObjectDocType = mobileSecurityObject.docType\n const docTypeResult: DocTypeMatchResult =\n document.docType !== docType\n ? {\n success: false,\n docType: document.docType,\n reason: `Document has docType '${document.docType}', but docType '${docType}' was requested`,\n }\n : mobileSecurityObjectDocType !== docType\n ? {\n success: false,\n docType: document.docType,\n reason: `Document has docType '${docType}', but the mobile security object has docType '${mobileSecurityObjectDocType}'`,\n }\n : { success: true, docType }\n\n const { claims, unusedElements } = matchElements({\n mode: 'verifier',\n namespaces,\n elements,\n issuerSigned: document.issuerSigned,\n keyAuthorizations: mobileSecurityObject.deviceKeyInfo.keyAuthorizations,\n deviceNamespaces: document.deviceSigned.deviceNamespaces,\n })\n const claimsResult: DocumentClaimsMatchResult = {\n ...toClaimsMatchResult(claims),\n unrequestedClaims: unusedElements,\n }\n\n return docTypeResult.success && claimsResult.success\n ? { documentIndex, success: true, docType: docTypeResult, claims: claimsResult }\n : { documentIndex, success: false, docType: docTypeResult, claims: claimsResult }\n })\n\n const validDocuments = documentMatches.filter((documentMatch) => documentMatch.success)\n const failedDocuments = documentMatches.filter((documentMatch) => !documentMatch.success)\n\n return isNonEmptyArray(validDocuments)\n ? { docRequestIndex, docType, success: true, validDocuments, failedDocuments }\n : { docRequestIndex, docType, success: false, validDocuments: [], failedDocuments }\n })\n\n const requestedDocTypes = new Set(deviceRequest.docRequests.map((docRequest) => docRequest.itemsRequest.docType))\n const unrequestedDocuments = documents.flatMap(({ document }, documentIndex) =>\n requestedDocTypes.has(document.docType) ? [] : [{ documentIndex, docType: document.docType }]\n )\n\n if (matchDocRequestsAsAlternatives(deviceRequest, matchOptions?.treatAmbiguousMultipleDocRequestsAsAlternatives)) {\n return docRequests.some((docRequest) => docRequest.success)\n ? { success: true, docRequestsAsAlternatives: true, docRequests, unrequestedDocuments }\n : { success: false, docRequestsAsAlternatives: true, docRequests, unrequestedDocuments }\n }\n\n return docRequests.every((docRequest) => docRequest.success)\n ? { success: true, docRequestsAsAlternatives: false, docRequests, unrequestedDocuments }\n : { success: false, docRequestsAsAlternatives: false, docRequests, unrequestedDocuments }\n}\n\n/**\n * Match the credentials of a holder against a `DeviceRequest` (holder side), to select which\n * credentials can answer which doc request.\n *\n * Reports per doc request, per credential and per check whether the credential satisfies the doc\n * request, so a holder can show which credentials match, and for a credential of the right docType\n * which requested elements it is missing. Every credential is matched against every doc request, and\n * is referred to by its index in `credentials`.\n *\n * A requested element is disclosed issuer-signed when the issuer signed it (or, for an\n * `age_over_NN` request, the age attestation 18013-5 7.2.5 allows in its place). Otherwise it is\n * disclosed device-signed when the credential comes with a value for exactly that element in its\n * `deviceNamespaces`, and the device key is authorized for it in the key authorizations of the MSO.\n *\n * `DeviceResponse.createWithDeviceRequest` selects the elements to disclose the same way, so a\n * credential that matches can answer the doc request with the same `deviceNamespaces`. The request\n * does not say which elements are optional, so every requested element is required.\n *\n * A doc request that asks for more than two `age_over_NN` elements in a namespace (18013-5 7.2.5)\n * is not matched against any credential, and fails with `invalidDocRequest`.\n *\n * By default the match only succeeds when every doc request can be answered. Pass\n * `treatAmbiguousMultipleDocRequestsAsAlternatives` to have it succeed when at least one can.\n *\n * Shares its matching with {@link matchDeviceRequest}: a credential matches like a verifier that\n * accepts every element from `'any'` source would match the response. A verifier only accepts\n * issuer-signed elements by default, so a device-signed element only satisfies it when its match\n * options allow `deviceSigned` for it.\n */\nexport const matchCredentialsToDeviceRequest = (options: {\n deviceRequest: DeviceRequest\n credentials: Array<IssuerSigned | HolderCredential>\n /**\n * See `DeviceRequestMatchOptions.treatAmbiguousMultipleDocRequestsAsAlternatives`. Defaults to\n * `false`.\n */\n treatAmbiguousMultipleDocRequestsAsAlternatives?: boolean\n}): HolderDeviceRequestMatchResult => {\n const { deviceRequest } = options\n const credentials = options.credentials.map((credential) => {\n const { issuerSigned, deviceNamespaces }: HolderCredential =\n credential instanceof IssuerSigned ? { issuerSigned: credential } : credential\n\n // Every access to the mobile security object decodes it, so decode it once per credential.\n return { issuerSigned, deviceNamespaces, mobileSecurityObject: issuerSigned.issuerAuth.mobileSecurityObject }\n })\n\n const docRequests = deviceRequest.docRequests.map((docRequest, docRequestIndex): HolderDocRequestMatch => {\n const { docType, namespaces } = docRequest.itemsRequest\n\n const ageOverLimitViolations = findAgeOverRequestLimitViolations(namespaces)\n if (ageOverLimitViolations.length > 0) {\n return {\n docRequestIndex,\n docType,\n success: false,\n validCredentials: [],\n failedCredentials: [],\n invalidDocRequest: {\n failure: 'ageOverLimitExceeded',\n reason: `Doc request ${docRequestIndex} requests ${describeAgeOverLimitViolations(ageOverLimitViolations)}, but at most two age_over_NN elements may be requested per namespace`,\n },\n }\n }\n\n const credentialMatches = credentials.map(\n ({ issuerSigned, deviceNamespaces, mobileSecurityObject }, credentialIndex): CredentialMatch => {\n const credentialDocType = mobileSecurityObject.docType\n const docTypeResult: DocTypeMatchResult =\n credentialDocType === docType\n ? { success: true, docType }\n : {\n success: false,\n docType: credentialDocType,\n reason: `Credential has docType '${credentialDocType}', but docType '${docType}' was requested`,\n }\n\n const claimsResult = toClaimsMatchResult(\n matchElements({\n mode: 'holder',\n namespaces,\n issuerSigned,\n keyAuthorizations: mobileSecurityObject.deviceKeyInfo.keyAuthorizations,\n deviceNamespaces,\n }).claims\n )\n\n return docTypeResult.success && claimsResult.success\n ? { credentialIndex, success: true, docType: docTypeResult, claims: claimsResult }\n : { credentialIndex, success: false, docType: docTypeResult, claims: claimsResult }\n }\n )\n\n const validCredentials = credentialMatches.filter((credentialMatch) => credentialMatch.success)\n const failedCredentials = credentialMatches.filter((credentialMatch) => !credentialMatch.success)\n\n return isNonEmptyArray(validCredentials)\n ? { docRequestIndex, docType, success: true, validCredentials, failedCredentials }\n : { docRequestIndex, docType, success: false, validCredentials: [], failedCredentials }\n })\n\n if (matchDocRequestsAsAlternatives(deviceRequest, options.treatAmbiguousMultipleDocRequestsAsAlternatives)) {\n return docRequests.some((docRequest) => docRequest.success)\n ? { success: true, docRequestsAsAlternatives: true, docRequests }\n : { success: false, docRequestsAsAlternatives: true, docRequests }\n }\n\n return docRequests.every((docRequest) => docRequest.success)\n ? { success: true, docRequestsAsAlternatives: false, docRequests }\n : { success: false, docRequestsAsAlternatives: false, docRequests }\n}\n\n/**\n * Whether the doc requests are matched as alternatives. A single doc request is not ambiguous, so it\n * always has to be satisfied.\n */\nconst matchDocRequestsAsAlternatives = (\n deviceRequest: DeviceRequest,\n treatAmbiguousMultipleDocRequestsAsAlternatives = false\n) => treatAmbiguousMultipleDocRequestsAsAlternatives && deviceRequest.docRequests.length > 1\n\ntype ElementCandidate = DisclosedElement & {\n /**\n * The issuer-signed item the element comes from, so a holder can disclose it as is.\n */\n issuerSignedItem?: IssuerSignedItem\n}\n\n/**\n * @internal\n */\nexport type ElementMatch =\n | {\n claim: ClaimMatchSuccess\n element: ElementCandidate\n }\n | { claim: ClaimMatchFailure; element?: undefined }\n\n/**\n * Match the requested elements of a single doc request against a single document or credential.\n * Shared by the verifier and the holder side.\n *\n * - `verifier` matches the elements a document disclosed, from the source the `elements` options\n * allow (by default `issuerSigned`).\n * - `holder` matches the elements a credential can disclose: issuer-signed when the issuer signed\n * it, and otherwise device-signed when `deviceNamespaces` has a value for exactly that element.\n * Device-signed values are provided by the holder itself, so an `age_over_NN` request is not\n * answered with a device-signed value for another age.\n *\n * Either way a device-signed element only answers a request when the device key is authorized for\n * it (18013-5 9.1.3.4).\n *\n * @internal\n */\nexport const matchElements = (options: {\n mode: 'holder' | 'verifier'\n namespaces: Map<Namespace, Map<DataElementIdentifier, IntentToRetain>>\n elements?: Record<Namespace, Record<DataElementIdentifier, ElementMatchOptions>>\n issuerSigned: IssuerSigned\n /**\n * The key authorizations in the mobile security object of `issuerSigned`, passed in so that the\n * caller decodes the mobile security object only once.\n */\n keyAuthorizations: KeyAuthorizations | undefined\n deviceNamespaces?: DeviceNamespaces\n}): { claims: Array<ElementMatch>; unusedElements: Array<DisclosedElement> } => {\n const { mode, namespaces, keyAuthorizations } = options\n\n const available = collectElements(options.issuerSigned, options.deviceNamespaces)\n\n const claims: Array<ElementMatch> = []\n const usedElements = new Set<DisclosedElement>()\n\n const success = (claim: ClaimMatchBase, element: ElementCandidate) => {\n usedElements.add(element)\n claims.push({\n element,\n claim: {\n ...claim,\n success: true,\n disclosedElementIdentifier: element.elementIdentifier,\n elementValue: element.elementValue,\n source: element.source,\n },\n })\n }\n\n const failure = (\n claim: ClaimMatchBase,\n failure: Pick<ClaimMatchFailure, 'failure' | 'disclosedFrom' | 'reason'>,\n // The elements the document disclosed for the claim, so they are not also reported as unrequested.\n ...disclosed: Array<ElementCandidate | undefined>\n ) => {\n for (const element of disclosed) if (element) usedElements.add(element)\n claims.push({ claim: { ...claim, success: false, ...failure } })\n }\n\n for (const [namespace, requestedElements] of namespaces) {\n const issuerSignedInNamespace = available.filter(\n (element) => element.namespace === namespace && element.source === 'issuerSigned'\n )\n const deviceSignedInNamespace = available.filter(\n (element) => element.namespace === namespace && element.source === 'deviceSigned'\n )\n // 18013-5 9.1.3.4: device-signed elements only answer a request when the device key is\n // authorized for them.\n const authorizedDeviceSignedInNamespace = deviceSignedInNamespace.filter((element) =>\n isDeviceSignedElementAuthorized(keyAuthorizations, element)\n )\n const namespaceOptions = getOwnProperty(options.elements, namespace)\n\n for (const [elementIdentifier, intentToRetain] of requestedElements) {\n if (mode === 'holder') {\n const claim = { namespace, elementIdentifier, intentToRetain, optional: false }\n\n const element =\n findElement(elementIdentifier, issuerSignedInNamespace) ??\n authorizedDeviceSignedInNamespace.find((candidate) => candidate.elementIdentifier === elementIdentifier)\n if (element) {\n success(claim, element)\n continue\n }\n\n failure(claim, {\n failure: 'notDisclosed',\n reason: isDeviceSignedElementAuthorized(keyAuthorizations, { namespace, elementIdentifier })\n ? `Element '${elementIdentifier}' in namespace '${namespace}' is not issuer-signed in the credential, so it has to be disclosed device-signed, but no value was provided for it in the device namespaces`\n : `Element '${elementIdentifier}' in namespace '${namespace}' is not issuer-signed in the credential, and the device key is not authorized to sign it`,\n })\n continue\n }\n\n const { optional = false, source = 'issuerSigned' } =\n getOwnProperty(namespaceOptions, elementIdentifier) ?? getOwnProperty(namespaceOptions, '*') ?? {}\n const claim = { namespace, elementIdentifier, intentToRetain, optional }\n\n // The source is applied before the element is picked, so that an `age_over_NN` request is not\n // answered by a device-signed attestation while an issuer-signed one is also present.\n const element =\n source === 'deviceSigned'\n ? findElement(elementIdentifier, authorizedDeviceSignedInNamespace)\n : (findElement(elementIdentifier, issuerSignedInNamespace) ??\n (source === 'any' ? findElement(elementIdentifier, authorizedDeviceSignedInNamespace) : undefined))\n\n if (element) {\n success(claim, element)\n continue\n }\n\n // The element may still be there, just not in a way this verifier accepts for it — report\n // that rather than letting it pass or reporting it as absent. Both are marked as used, as the\n // doc request did ask for the element.\n //\n // Disclosed from a source that is not allowed:\n const disallowed =\n source === 'any'\n ? undefined\n : findElement(\n elementIdentifier,\n source === 'issuerSigned' ? deviceSignedInNamespace : issuerSignedInNamespace\n )\n // Disclosed device-signed from an allowed source, but every authorized element was already\n // tried above:\n const unauthorized =\n source === 'issuerSigned' ? undefined : findElement(elementIdentifier, deviceSignedInNamespace)\n\n // The unauthorized element is the one disclosed from the allowed source, so it is the failure\n // to report when both are there.\n if (unauthorized) {\n failure(\n claim,\n {\n failure: 'deviceKeyNotAuthorized',\n disclosedFrom: 'deviceSigned',\n reason: `Element '${unauthorized.elementIdentifier}' in namespace '${namespace}' was disclosed through deviceSigned, but the device key is not authorized for it in the mobile security object`,\n },\n unauthorized,\n disallowed\n )\n continue\n }\n\n if (disallowed) {\n failure(\n claim,\n {\n failure: 'disallowedSource',\n disclosedFrom: disallowed.source,\n reason: `Element '${disallowed.elementIdentifier}' in namespace '${namespace}' was disclosed through ${disallowed.source}, but must be disclosed through ${source}`,\n },\n disallowed\n )\n continue\n }\n\n failure(claim, {\n failure: 'notDisclosed',\n reason: `Element '${elementIdentifier}' in namespace '${namespace}' was not disclosed`,\n })\n }\n }\n\n return {\n claims,\n unusedElements: available\n .filter((element) => !usedElements.has(element))\n .map(({ issuerSignedItem: _, ...element }) => element),\n }\n}\n\nconst toClaimsMatchResult = (claims: Array<ElementMatch>): ClaimsMatchResult => {\n const validClaims = claims.flatMap(({ claim }) => (claim.success ? [claim] : []))\n const failedClaims = claims.flatMap(({ claim }) => (claim.success ? [] : [claim]))\n\n if (isNonEmptyArray(failedClaims) && failedClaims.some((claim) => !claim.optional)) {\n return { success: false, validClaims, failedClaims }\n }\n\n // Every failed claim is optional, and optional elements never make the claims fail.\n return { success: true, validClaims, failedClaims: failedClaims.filter(isOptionalClaim) }\n}\n\nconst isOptionalClaim = (claim: ClaimMatchFailure): claim is ClaimMatchFailure & { optional: true } => claim.optional\n\n/**\n * The match options per doc request index, after checking that every option refers to a doc request\n * of the device request, and that no doc request has options more than once.\n */\nconst indexDocRequestOptions = (deviceRequest: DeviceRequest, matchOptions?: DeviceRequestMatchOptions) => {\n const docRequestOptions = new Map<number, DocRequestMatchOptions>()\n\n for (const options of matchOptions?.docRequests ?? []) {\n const { docRequestIndex } = options\n if (\n !Number.isInteger(docRequestIndex) ||\n docRequestIndex < 0 ||\n docRequestIndex >= deviceRequest.docRequests.length\n ) {\n throw new InvalidDeviceRequestMatchOptionsError(\n `Match options refer to doc request ${docRequestIndex}, but the device request has ${deviceRequest.docRequests.length} doc request(s)`\n )\n }\n if (docRequestOptions.has(docRequestIndex)) {\n throw new InvalidDeviceRequestMatchOptionsError(\n `Match options are provided more than once for doc request ${docRequestIndex}`\n )\n }\n docRequestOptions.set(docRequestIndex, options)\n }\n\n return docRequestOptions\n}\n\n/**\n * Throw an `InvalidDeviceRequestMatchOptionsError` when the match options do not fit the device\n * request, so that verification can fail on them before it does any work.\n *\n * @internal\n */\nexport const validateDeviceRequestMatchOptions = (\n deviceRequest: DeviceRequest,\n matchOptions?: DeviceRequestMatchOptions\n) => {\n indexDocRequestOptions(deviceRequest, matchOptions)\n}\n\nconst isNonEmptyArray = <T>(array: Array<T>): array is NonEmptyArray<T> => array.length > 0\n\n/**\n * The element that answers a request for `elementIdentifier`, either by identifier or, for an age\n * attestation, by the substitution 18013-5 7.2.5 allows.\n *\n * @internal\n */\nexport const findElement = <Candidate extends { elementIdentifier: DataElementIdentifier; elementValue: unknown }>(\n elementIdentifier: DataElementIdentifier,\n candidates: Array<Candidate>\n) =>\n candidates.find((candidate) => candidate.elementIdentifier === elementIdentifier) ??\n findAgeOverCandidate(elementIdentifier, candidates)\n\nconst collectElements = (issuerSigned: IssuerSigned, deviceNamespaces?: DeviceNamespaces) => {\n const elements: Array<ElementCandidate> = []\n\n for (const [namespace, issuerSignedItems] of issuerSigned.issuerNamespaces?.issuerNamespaces ?? []) {\n for (const issuerSignedItem of issuerSignedItems) {\n elements.push({\n namespace,\n elementIdentifier: issuerSignedItem.elementIdentifier,\n elementValue: issuerSignedItem.elementValue,\n source: 'issuerSigned',\n issuerSignedItem,\n })\n }\n }\n\n for (const [namespace, deviceSignedItems] of deviceNamespaces?.deviceNamespaces ?? []) {\n for (const [elementIdentifier, elementValue] of deviceSignedItems.deviceSignedItems) {\n elements.push({ namespace, elementIdentifier, elementValue, source: 'deviceSigned' })\n }\n }\n\n return elements\n}\n\n/**\n * Report a {@link DeviceRequestMatchResult} through a verification callback.\n *\n * A doc request that is not satisfied is a `FAILED` check; over-disclosure and documents that were\n * never requested are reported as `WARNING`, as they are the mdoc's doing and it is up to the\n * verifier whether to accept the response anyway. When the doc requests are matched as alternatives,\n * a single check is reported instead, which only fails when none of them is satisfied.\n *\n * The match is attached to the doc request checks as their structured `result`, so that it survives\n * a callback that throws on a `FAILED` check instead of collecting them.\n */\nexport const reportDeviceRequestMatch = (match: DeviceRequestMatchResult, onCheck: VerificationCallback) => {\n const result = { type: 'deviceRequestMatch', match } as const\n\n if (match.docRequestsAsAlternatives) {\n const check = `Device response must satisfy at least one of the alternative doc requests ${match.docRequests\n .map((docRequest) => `${docRequest.docRequestIndex} for docType '${docRequest.docType}'`)\n .join(', ')}`\n\n if (match.success) {\n onCheck({ status: 'PASSED', check, category: 'DOCUMENT_FORMAT', result })\n } else {\n onCheck({\n status: 'FAILED',\n check,\n category: 'DOCUMENT_FORMAT',\n reason: match.docRequests\n .map((docRequest) => `Doc request ${docRequest.docRequestIndex}: ${docRequestFailureReason(docRequest)}`)\n .join('. '),\n result,\n })\n }\n } else {\n for (const docRequest of match.docRequests) {\n const check = `Device response must satisfy doc request ${docRequest.docRequestIndex} for docType '${docRequest.docType}'`\n\n if (docRequest.success) {\n onCheck({ status: 'PASSED', check, category: 'DOCUMENT_FORMAT', result })\n } else {\n onCheck({\n status: 'FAILED',\n check,\n category: 'DOCUMENT_FORMAT',\n reason: docRequestFailureReason(docRequest),\n result,\n })\n }\n }\n }\n\n for (const { documentIndex, docRequestIndexes, unrequestedClaims } of findOverDisclosure(match)) {\n const docRequests =\n docRequestIndexes.length === 1\n ? `doc request ${docRequestIndexes[0]}`\n : `doc requests ${docRequestIndexes.join(', ')}`\n\n onCheck({\n status: 'WARNING',\n check: `Document ${documentIndex} must not disclose elements that were not requested`,\n category: 'DOCUMENT_FORMAT',\n reason: `Document ${documentIndex} disclosed ${unrequestedClaims\n .map((claim) => `'${claim.elementIdentifier}' in namespace '${claim.namespace}'`)\n .join(', ')}, which ${docRequests} did not ask for`,\n })\n }\n\n if (match.unrequestedDocuments.length > 0) {\n onCheck({\n status: 'WARNING',\n check: 'Device response must not contain documents that were not requested',\n category: 'DOCUMENT_FORMAT',\n reason: `Device response contains ${match.unrequestedDocuments\n .map((document) => `document ${document.documentIndex} with docType '${document.docType}'`)\n .join(', ')}, which the device request did not ask for`,\n })\n }\n}\n\n/**\n * Per document, the elements it disclosed that no doc request it may answer asked for, in response\n * order. The response does not say which doc request a document answers, so every doc request of\n * its docType is considered, also one the document fails: with two doc requests of the same\n * docType, an element is only over-disclosed when neither asks for it. A document of another docType\n * does not answer the doc request, and is reported as an unrequested document instead.\n */\nconst findOverDisclosure = (match: DeviceRequestMatchResult) => {\n const documents = new Map<number, { docRequestIndexes: Array<number>; unrequestedClaims: Array<DisclosedElement> }>()\n\n for (const docRequest of match.docRequests) {\n for (const document of [...docRequest.validDocuments, ...docRequest.failedDocuments]) {\n if (!document.docType.success) continue\n\n const { unrequestedClaims } = document.claims\n const overDisclosure = documents.get(document.documentIndex)\n if (!overDisclosure) {\n documents.set(document.documentIndex, { docRequestIndexes: [docRequest.docRequestIndex], unrequestedClaims })\n continue\n }\n\n overDisclosure.docRequestIndexes.push(docRequest.docRequestIndex)\n overDisclosure.unrequestedClaims = overDisclosure.unrequestedClaims.filter((claim) =>\n unrequestedClaims.some(\n (other) =>\n other.namespace === claim.namespace &&\n other.elementIdentifier === claim.elementIdentifier &&\n other.source === claim.source\n )\n )\n }\n }\n\n return Array.from(documents, ([documentIndex, overDisclosure]) => ({ documentIndex, ...overDisclosure }))\n .filter(({ unrequestedClaims }) => unrequestedClaims.length > 0)\n .sort((a, b) => a.documentIndex - b.documentIndex)\n}\n\nconst docRequestFailureReason = (docRequest: DocRequestMatch) => {\n // Documents of another docType are not an attempt to answer this doc request.\n const documents = docRequest.failedDocuments.filter(\n (document) => document.docType.success || document.docType.docType === docRequest.docType\n )\n\n if (documents.length === 0) {\n return `Device response does not contain a document with docType '${docRequest.docType}'`\n }\n\n return documents\n .map((document) => {\n if (!document.docType.success) return `Document ${document.documentIndex}: ${document.docType.reason}`\n\n const failedClaims = document.claims.failedClaims.filter((claim) => !claim.optional)\n return `Document ${document.documentIndex}: ${failedClaims.map((claim) => claim.reason).join('; ')}`\n })\n .join('. ')\n}\n","import { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { DeviceAuth, type DeviceAuthEncodedStructure } from './device-auth'\nimport { DeviceNamespaces } 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 map.set('nameSpaces', DeviceNamespaces.fromDataItem(input.get('nameSpaces')))\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 // `DeviceNameSpacesBytes` are embedded as received, as device authentication covers them.\n map.set('nameSpaces', output.get('nameSpaces').asDataItem)\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 get errorItems() {\n return this.structure\n }\n\n public getErrorCode(dataElementIdentifier: DataElementIdentifier) {\n return this.structure.get(dataElementIdentifier)\n }\n\n public static create(options: ErrorItemsOptions) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(options.errorItems)\n }\n}\n","import { CborStructure } from '@owf/cose'\nimport z from 'zod'\nimport { ErrorItems, errorItemsSchema } from './error-items'\nimport type { Namespace } from './namespace'\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 /**\n * Map where keys are namespaces and values are the errored data elements within that namespace\n */\n public get errors() {\n return this.structure\n }\n\n public getErrorItems(namespace: Namespace) {\n return this.structure.get(namespace)\n }\n\n public static create(options: ErrorsOptions) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(options.errors)\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 { Errors, type ErrorsEncodedStructure } from './errors'\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.instanceof(Errors).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?: Errors\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', Errors.fromEncodedStructure(input.get('errors') as ErrorsEncodedStructure))\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 const errors = output.get('errors')\n if (errors) {\n map.set('errors', errors.encodedStructure)\n }\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import { CborStructure } from '@owf/cose'\nimport { z } from 'zod'\n\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 MacAlgorithm,\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 { describeAgeOverLimitViolations, findAgeOverLimitViolations } from '../../utils/ageOver'\nimport { getOwnProperty } from '../../utils/getOwnProperty'\nimport {\n describeUnauthorizedDeviceSignedElements,\n findUnauthorizedDeviceSignedElements,\n} from '../../utils/keyAuthorizations'\nimport {\n type ClaimMatch,\n type DeviceRequestMatchOptions,\n type DeviceRequestMatchResult,\n matchDeviceRequest,\n matchElements,\n reportDeviceRequestMatch,\n validateDeviceRequestMatchOptions,\n} from '../../utils/matchDeviceRequest'\nimport { verifyVersion } from '../../utils/version'\nimport { defaultVerificationCallback, type VerificationCallback } from '../check-callback'\nimport {\n AgeOverLimitExceededError,\n DeviceKeyNotAuthorizedError,\n DocTypeMismatchError,\n EitherSignatureOrMacMustBeProvidedError,\n InvalidElementSelectionError,\n MissingRequestedElementError,\n} from '../errors'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport type { DataElementValue } from './data-element-value'\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 { DeviceSignedItems } from './device-signed-items'\nimport type { DocRequest } from './doc-request'\nimport { Document, type DocumentEncodedStructure } from './document'\nimport { DocumentError, type DocumentErrorStructure } from './document-error'\nimport type { IssuerAuthVerificationResult } from './issuer-auth'\nimport { IssuerNamespaces } from './issuer-namespaces'\nimport { IssuerSigned } from './issuer-signed'\nimport type { IssuerSignedItem } from './issuer-signed-item'\nimport type { KeyAuthorizations } from './key-authorizations'\nimport type { Namespace } from './namespace'\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 DocumentVerificationResult = IssuerAuthVerificationResult & { document: Document }\n\nexport type DeviceResponseVerificationResult = {\n /**\n * One entry per document in the device response, in response order.\n */\n documents: Array<DocumentVerificationResult>\n /**\n * How the response matches the device request, per doc request and per requested element. Only\n * present when `deviceRequest` was provided.\n */\n deviceRequestMatch?: DeviceRequestMatchResult\n}\n\n/**\n * A single document to disclose in a device response, authenticated with either a device signature\n * or a device MAC.\n */\nexport type DeviceResponseDocumentOptions = {\n issuerSigned: IssuerSigned\n /**\n * Index into `deviceRequest.docRequests` of the doc request this document answers.\n */\n docRequestIndex: number\n /**\n * The requested elements to disclose, per namespace. Defaults to every element the doc request\n * asks for. Pass a subset to leave out elements, for instance the ones the user declined to share.\n *\n * Two `age_over_NN` requests can be answered with the same age attestation (18013-5 7.2.5), which\n * `disclosedElementIdentifier` of the claims of `Holder.matchDeviceRequest` shows. Such elements\n * have to be selected together or left out together, as leaving out only one would not keep its\n * answer from being disclosed.\n */\n elements?: Record<Namespace, Array<DataElementIdentifier>>\n /**\n * Values to disclose device-signed. Every selected requested element that is not issuer-signed,\n * but that the device key is authorized for in the MSO, has to be provided here. Only the values\n * of selected requested elements are disclosed and authenticated, so a value that is not requested\n * or that `elements` leaves out is not.\n */\n deviceNamespaces?: DeviceNamespaces\n signature?: {\n signingKey: CoseKey\n }\n mac?: {\n ephemeralKey: CoseKey\n signingKey: CoseKey\n }\n}\n\nexport class DeviceResponse extends CborStructure<DeviceResponseEncodedStructure, DeviceResponseDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(deviceResponseEncodedSchema.in, deviceResponseDecodedSchema.out, {\n decode: (input) => {\n const map = TypedMap.fromMap(input) as DeviceResponseDecodedStructure\n\n if (input.has('documents')) {\n map.set(\n 'documents',\n (input.get('documents') as unknown[]).map((d) =>\n Document.fromEncodedStructure(d as DocumentEncodedStructure)\n )\n )\n }\n\n if (input.has('documentErrors')) {\n map.set(\n 'documentErrors',\n (input.get('documentErrors') as unknown[]).map((d) =>\n DocumentError.fromEncodedStructure(d as DocumentErrorStructure)\n )\n )\n }\n\n return map\n },\n encode: (output) => {\n const map: Map<unknown, unknown> = output.toMap()\n\n const documents = output.get('documents')\n if (documents !== undefined) {\n map.set(\n 'documents',\n documents.map((d) => d.encodedStructure)\n )\n }\n\n const documentErrors = output.get('documentErrors')\n if (documentErrors !== undefined) {\n map.set(\n 'documentErrors',\n documentErrors.map((d) => d.encodedStructure)\n )\n }\n\n return map\n },\n })\n }\n\n public get version() {\n return this.structure.get('version')\n }\n\n public get documents() {\n return this.structure.get('documents')\n }\n\n public get documentErrors() {\n return this.structure.get('documentErrors')\n }\n\n public get status() {\n return this.structure.get('status')\n }\n\n public async verify(\n options: {\n deviceRequest?: DeviceRequest\n deviceRequestMatchOptions?: DeviceRequestMatchOptions\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 // Invalid match options are a mistake of the caller, so fail on them before verifying anything.\n if (options.deviceRequest) {\n validateDeviceRequestMatchOptions(options.deviceRequest, options.deviceRequestMatchOptions)\n }\n\n verifyVersion({ structure: 'Device Response', version: this.structure.get('version') }, onCheck)\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 // 18013-5 8.3.2.1.2.3 Table 8: an mdoc returning a status other than 0 must not return documents.\n const status = this.structure.get('status')\n onCheck({\n status: status === 0 || !documents?.length ? 'PASSED' : 'FAILED',\n check: 'Device Response must not include documents when the status is not 0.',\n category: 'DOCUMENT_FORMAT',\n reason:\n status !== 0 && documents?.length\n ? `Device Response has status ${status} but returned ${documents.length} document(s)`\n : undefined,\n })\n\n const documentResults: Array<DocumentVerificationResult> = []\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\n // 18013-5 9.3.1 step 4: the docType of the document is not signed, so it must be the docType of\n // the MSO, whether or not a device request is matched.\n const mobileSecurityObjectDocType = document.issuerSigned.issuerAuth.mobileSecurityObject.docType\n onCheck({\n status: document.docType === mobileSecurityObjectDocType ? 'PASSED' : 'FAILED',\n check: 'The docType of the document must match the docType of the mobile security object.',\n category: 'ISSUER_AUTH',\n reason:\n document.docType !== mobileSecurityObjectDocType\n ? `Document has docType '${document.docType}', but the mobile security object has docType '${mobileSecurityObjectDocType}'`\n : undefined,\n })\n\n documentResults.push({\n trustedIssuanceChain,\n statusList,\n trustedStatusListChain,\n identifierList,\n trustedIdentifierListChain,\n document,\n })\n }\n\n let deviceRequestMatch: DeviceRequestMatchResult | undefined\n if (options.deviceRequest) {\n deviceRequestMatch = matchDeviceRequest({\n deviceRequest: options.deviceRequest,\n deviceResponse: this,\n matchOptions: options.deviceRequestMatchOptions,\n })\n reportDeviceRequestMatch(deviceRequestMatch, onCheck)\n }\n\n return { documents: documentResults, deviceRequestMatch }\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 /**\n * Create a single disclosed `Document` for one `DocRequest`, authenticated with either a\n * device signature or a device MAC.\n */\n private static async createDocument(\n options: {\n docRequest: DocRequest\n docRequestIndex: number\n sessionTranscript: SessionTranscript | Uint8Array\n issuerSigned: IssuerSigned\n elements?: Record<Namespace, Array<DataElementIdentifier>>\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 { docRequest } = options\n const docType = docRequest.itemsRequest.docType\n\n // Every access to the mobile security object decodes it, so decode it once.\n const mobileSecurityObject = options.issuerSigned.issuerAuth.mobileSecurityObject\n const { keyAuthorizations } = mobileSecurityObject.deviceKeyInfo\n\n // The document is labeled with the requested docType, which is not signed, so a credential of\n // another docType would produce a document every reader has to reject.\n if (mobileSecurityObject.docType !== docType) {\n throw new DocTypeMismatchError(\n `Credential has docType '${mobileSecurityObject.docType}', but doc request ${options.docRequestIndex} requests docType '${docType}'`\n )\n }\n\n // Only the selected elements are disclosed, so values in `deviceNamespaces` that are not requested\n // do not need to be authorized, the same as `Holder.matchDeviceRequest` ignores them.\n const { issuerNamespaces: disclosedIssuerNamespaces, deviceNamespaces } = DeviceResponse.selectElements({\n docRequest,\n issuerSigned: options.issuerSigned,\n keyAuthorizations,\n deviceNamespaces: options.deviceNamespaces,\n elements: options.elements,\n })\n\n // 18013-5 9.1.3.4 binds the mdoc as well as the mdoc reader. Selection only picks authorized\n // device-signed elements, so this guards that invariant rather than emit a response every reader\n // must reject.\n const unauthorized = findUnauthorizedDeviceSignedElements({ deviceNamespaces, keyAuthorizations })\n if (unauthorized.length > 0) {\n throw new DeviceKeyNotAuthorizedError(describeUnauthorizedDeviceSignedElements(unauthorized))\n }\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 deviceAuthOptions: DeviceAuthOptions = {}\n if (useSignature) {\n const deviceSignature = await DeviceSignature.create({\n unprotectedHeaders,\n protectedHeaders: ProtectedHeaders.create({\n protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.Algorithm, signingKey.algorithm]]),\n }),\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 // 18013-5 9.1.3.5: the device MAC is always HMAC 256/256, keyed with the EMacKey derived from\n // the device key, and not with the algorithm of the device key.\n const deviceMac = DeviceMac.create({\n protectedHeaders: ProtectedHeaders.create({\n protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.Algorithm, MacAlgorithm.HS256]]),\n }),\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(\n { key: macKey, algorithm: MacAlgorithm.HS256, detachedPayload: deviceAuthenticationBytes },\n ctx.cose.mac0\n )\n\n deviceAuthOptions.deviceMac = deviceMac\n }\n\n return Document.create({\n docType,\n issuerSigned: IssuerSigned.create({\n issuerNamespaces: disclosedIssuerNamespaces,\n issuerAuth: options.issuerSigned.issuerAuth,\n }),\n deviceSigned: DeviceSigned.create({\n deviceNamespaces,\n deviceAuth: DeviceAuth.create(deviceAuthOptions),\n }),\n })\n }\n\n /**\n * The issuer-signed items and device-signed elements to disclose for a doc request, selected the\n * same way as `Holder.matchDeviceRequest` matches a credential: a requested element is disclosed\n * issuer-signed when the issuer signed it, and otherwise device-signed when the device key is\n * authorized for it and its value is in the device namespaces.\n *\n * Only the selected requested elements are disclosed, from either source: a device-signed element\n * that is not requested, or that `elements` leaves out, is not disclosed.\n */\n private static selectElements(options: {\n docRequest: DocRequest\n issuerSigned: IssuerSigned\n keyAuthorizations: KeyAuthorizations | undefined\n deviceNamespaces?: DeviceNamespaces\n elements?: Record<Namespace, Array<DataElementIdentifier>>\n }) {\n const { claims } = matchElements({\n mode: 'holder',\n namespaces: options.docRequest.itemsRequest.namespaces,\n issuerSigned: options.issuerSigned,\n keyAuthorizations: options.keyAuthorizations,\n deviceNamespaces: options.deviceNamespaces,\n })\n\n if (options.elements) {\n for (const [namespace, elementIdentifiers] of Object.entries(options.elements)) {\n for (const elementIdentifier of elementIdentifiers) {\n if (!options.docRequest.itemsRequest.namespaces.get(namespace)?.has(elementIdentifier)) {\n throw new InvalidElementSelectionError(\n `Element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but the doc request does not request it`\n )\n }\n }\n }\n }\n\n const isSelected = ({ namespace, elementIdentifier }: ClaimMatch) =>\n options.elements ? (getOwnProperty(options.elements, namespace)?.includes(elementIdentifier) ?? false) : true\n\n // The element that answers each requested element left out of the selection, with that claim.\n const declinedElements = new Map(\n claims.flatMap(({ claim, element }) => (element && !isSelected(claim) ? [[element, claim] as const] : []))\n )\n\n const issuerNamespaces = new Map<Namespace, Array<IssuerSignedItem>>()\n const deviceNamespaces = new Map<Namespace, Map<DataElementIdentifier, DataElementValue>>()\n for (const match of claims) {\n const { claim } = match\n if (!isSelected(claim)) continue\n\n if (match.element === undefined) throw new MissingRequestedElementError(match.claim.reason)\n const { element } = match\n\n // An age attestation can answer more than one `age_over_NN` request (18013-5 7.2.5).\n // Disclosing it for this element would also answer a requested element that is left out, so\n // leaving that one out would have no effect.\n const declined = declinedElements.get(element)\n if (declined) {\n throw new InvalidElementSelectionError(\n `Element '${claim.elementIdentifier}' in namespace '${claim.namespace}' is selected for disclosure, but it is answered with '${element.elementIdentifier}', which also answers '${declined.elementIdentifier}' that is not selected. Select both or neither`\n )\n }\n\n if (!element.issuerSignedItem) {\n const items = deviceNamespaces.get(element.namespace) ?? new Map()\n items.set(element.elementIdentifier, element.elementValue)\n deviceNamespaces.set(element.namespace, items)\n continue\n }\n\n const items = issuerNamespaces.get(claim.namespace) ?? []\n // An age attestation can answer more than one `age_over_NN` request, but is disclosed once.\n if (!items.includes(element.issuerSignedItem)) items.push(element.issuerSignedItem)\n issuerNamespaces.set(claim.namespace, items)\n }\n\n // 18013-5 7.2.5: a reader must not request more than two age attestations, as together they\n // narrow down the age of the holder. Only what is disclosed counts, so a holder can still answer\n // such a request by selecting at most two of them.\n const disclosedElementIdentifiers = new Map<Namespace, Array<DataElementIdentifier>>(\n Array.from(issuerNamespaces, ([namespace, items]) => [namespace, items.map((item) => item.elementIdentifier)])\n )\n for (const [namespace, items] of deviceNamespaces) {\n disclosedElementIdentifiers.set(namespace, [\n ...(disclosedElementIdentifiers.get(namespace) ?? []),\n ...items.keys(),\n ])\n }\n const ageOverLimitViolations = findAgeOverLimitViolations(disclosedElementIdentifiers)\n if (ageOverLimitViolations.length > 0) {\n throw new AgeOverLimitExceededError(\n `Doc request would be answered with ${describeAgeOverLimitViolations(ageOverLimitViolations)}, but at most two age_over_NN elements may be disclosed per namespace. Select at most two of them`\n )\n }\n\n return {\n // `IssuerNameSpaces` must have at least one namespace, so it is left out when no issuer-signed\n // element is disclosed.\n issuerNamespaces: issuerNamespaces.size > 0 ? IssuerNamespaces.create({ issuerNamespaces }) : undefined,\n deviceNamespaces: DeviceNamespaces.create({\n deviceNamespaces: new Map(\n Array.from(deviceNamespaces, ([namespace, items]) => [\n namespace,\n DeviceSignedItems.create({ deviceSignedItems: items }),\n ])\n ),\n }),\n }\n }\n\n private static fromDocuments(documents: Array<Document>) {\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 private static findDocRequest(deviceRequest: DeviceRequest, docRequestIndex: number): DocRequest {\n const docRequest = deviceRequest.docRequests[docRequestIndex]\n if (!docRequest) throw new Error(`No doc request found at index ${docRequestIndex}`)\n\n return docRequest\n }\n\n /**\n * Create a device response for a device request.\n *\n * Every document brings its own device key and, optionally, its own device namespaces, and names\n * the doc request it answers through `docRequestIndex`, so a request may also be answered\n * partially.\n */\n public static async createWithDeviceRequest(\n options: {\n deviceRequest: DeviceRequest\n sessionTranscript: SessionTranscript | Uint8Array\n documents: Array<DeviceResponseDocumentOptions>\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose'>\n ) {\n const documents = await Promise.all(\n options.documents.map((document) =>\n DeviceResponse.createDocument(\n {\n docRequest: DeviceResponse.findDocRequest(options.deviceRequest, document.docRequestIndex),\n docRequestIndex: document.docRequestIndex,\n sessionTranscript: options.sessionTranscript,\n issuerSigned: document.issuerSigned,\n elements: document.elements,\n deviceNamespaces: document.deviceNamespaces,\n signature: document.signature,\n mac: document.mac,\n },\n ctx\n )\n )\n )\n\n return DeviceResponse.fromDocuments(documents)\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import { CborStructure, TypedMap, typedMap, zUint8Array } from '@owf/cose'\nimport type { z } from 'zod'\n\nconst encryptedResponseDataSchema = typedMap([\n ['enc', zUint8Array],\n ['cipherText', zUint8Array],\n] as const)\n\nexport type EncryptedResponseDataDecodedStructure = z.output<typeof encryptedResponseDataSchema>\nexport type EncryptedResponseDataEncodedStructure = z.input<typeof encryptedResponseDataSchema>\n\nexport type EncryptedResponseDataOptions = {\n /**\n * Raw serialized HPKE encapsulated key. For DHKEM(P-256) this is the 65-byte\n * uncompressed SEC1 point, not a COSE_Key.\n */\n enc: Uint8Array\n ciphertext: Uint8Array\n}\n\n/**\n * EncryptedResponseData as defined in ISO/IEC TS 18013-7:2025 C.3.\n *\n * EncryptedResponseData = { \"enc\": bstr, \"cipherText\": bstr }\n */\nexport class EncryptedResponseData extends CborStructure<\n EncryptedResponseDataEncodedStructure,\n EncryptedResponseDataDecodedStructure\n> {\n public static override get encodingSchema() {\n return encryptedResponseDataSchema\n }\n\n public get enc() {\n return this.structure.get('enc')\n }\n\n public get ciphertext() {\n return this.structure.get('cipherText')\n }\n\n public static create(options: EncryptedResponseDataOptions): EncryptedResponseData {\n const map: EncryptedResponseDataDecodedStructure = new TypedMap([\n ['enc', options.enc],\n ['cipherText', options.ciphertext],\n ])\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import { CborStructure } from '@owf/cose'\nimport { base64url } from '@owf/identity-common'\nimport { z } from 'zod'\nimport { EncryptedResponseData, type EncryptedResponseDataEncodedStructure } from './encrypted-response-data'\n\nconst encryptedResponseEncodedSchema = z.tuple([z.literal('dcapi'), z.map(z.unknown(), z.unknown())])\nconst encryptedResponseDecodedSchema = z.instanceof(EncryptedResponseData)\n\nexport type EncryptedResponseEncodedStructure = z.infer<typeof encryptedResponseEncodedSchema>\nexport type EncryptedResponseDecodedStructure = z.infer<typeof encryptedResponseDecodedSchema>\n\nexport type EncryptedResponseOptions = {\n encryptedResponseData: EncryptedResponseData\n}\n\n/**\n * EncryptedResponse as defined in ISO/IEC TS 18013-7:2025 C.3.\n *\n * EncryptedResponse = [ \"dcapi\", EncryptedResponseData ]\n */\nexport class EncryptedResponse extends CborStructure<\n EncryptedResponseEncodedStructure,\n EncryptedResponseDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(encryptedResponseEncodedSchema, encryptedResponseDecodedSchema, {\n decode: ([, encryptedResponseData]) =>\n EncryptedResponseData.fromEncodedStructure(encryptedResponseData as EncryptedResponseDataEncodedStructure),\n encode: (encryptedResponseData) =>\n ['dcapi', encryptedResponseData.encodedStructure] satisfies EncryptedResponseEncodedStructure,\n })\n }\n\n public get encryptedResponseData() {\n return this.structure\n }\n\n public get enc() {\n return this.structure.enc\n }\n\n public get ciphertext() {\n return this.structure.ciphertext\n }\n\n public static create(options: EncryptedResponseOptions): EncryptedResponse {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(options.encryptedResponseData)\n }\n\n public static fromBase64Url(encryptedResponse: string): EncryptedResponse {\n // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\n return this.decode(base64url.decode(encryptedResponse))\n }\n\n public toBase64Url(): string {\n return base64url.encode(this.encode())\n }\n}\n","import { CborStructure, CoseKey, type CoseKeyEncodedStructure, TypedMap, typedMap, zUint8Array } from '@owf/cose'\nimport { z } from 'zod'\n\nconst encryptionParametersSchema = typedMap([\n ['nonce', zUint8Array],\n ['recipientPublicKey', z.instanceof(CoseKey)],\n] as const)\n\nexport type EncryptionParametersDecodedStructure = z.output<typeof encryptionParametersSchema>\nexport type EncryptionParametersEncodedStructure = z.input<typeof encryptionParametersSchema>\n\nexport type EncryptionParametersOptions = {\n nonce: Uint8Array\n recipientPublicKey: CoseKey\n}\n\n/**\n * EncryptionParameters as defined in ISO/IEC TS 18013-7:2025 C.2.\n *\n * EncryptionParameters = { \"nonce\": bstr, \"recipientPublicKey\": COSE_Key }\n */\nexport class EncryptionParameters extends CborStructure<\n EncryptionParametersEncodedStructure,\n EncryptionParametersDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(encryptionParametersSchema.in, encryptionParametersSchema.out, {\n decode: (input) => {\n const map = TypedMap.fromMap(input) as EncryptionParametersDecodedStructure\n\n map.set(\n 'recipientPublicKey',\n CoseKey.fromEncodedStructure(input.get('recipientPublicKey') as CoseKeyEncodedStructure)\n )\n\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n map.set('recipientPublicKey', output.get('recipientPublicKey').encodedStructure)\n\n return map\n },\n })\n }\n\n public get nonce() {\n return this.structure.get('nonce')\n }\n\n public get recipientPublicKey() {\n return this.structure.get('recipientPublicKey')\n }\n\n public static create(options: EncryptionParametersOptions): EncryptionParameters {\n const map: EncryptionParametersDecodedStructure = new TypedMap([\n ['nonce', options.nonce],\n ['recipientPublicKey', options.recipientPublicKey],\n ])\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import { CborStructure } from '@owf/cose'\nimport { base64url } from '@owf/identity-common'\nimport { z } from 'zod'\nimport { EncryptionParameters, type EncryptionParametersEncodedStructure } from './encryption-parameters'\n\nconst encryptionInfoEncodedSchema = z.tuple([z.literal('dcapi'), z.map(z.unknown(), z.unknown())])\nconst encryptionInfoDecodedSchema = z.instanceof(EncryptionParameters)\n\nexport type EncryptionInfoEncodedStructure = z.infer<typeof encryptionInfoEncodedSchema>\nexport type EncryptionInfoDecodedStructure = z.infer<typeof encryptionInfoDecodedSchema>\n\nexport type EncryptionInfoOptions = {\n encryptionParameters: EncryptionParameters\n}\n\n/**\n * EncryptionInfo as defined in ISO/IEC TS 18013-7:2025 C.2.\n *\n * EncryptionInfo = [ \"dcapi\", EncryptionParameters ]\n */\nexport class EncryptionInfo extends CborStructure<EncryptionInfoEncodedStructure, EncryptionInfoDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(encryptionInfoEncodedSchema, encryptionInfoDecodedSchema, {\n decode: ([, encryptionParameters]) =>\n EncryptionParameters.fromEncodedStructure(encryptionParameters as EncryptionParametersEncodedStructure),\n encode: (encryptionParameters) =>\n ['dcapi', encryptionParameters.encodedStructure] satisfies EncryptionInfoEncodedStructure,\n })\n }\n\n public get encryptionParameters() {\n return this.structure\n }\n\n public get nonce() {\n return this.structure.nonce\n }\n\n public get recipientPublicKey() {\n return this.structure.recipientPublicKey\n }\n\n public static create(options: EncryptionInfoOptions): EncryptionInfo {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(options.encryptionParameters)\n }\n\n public static fromBase64Url(encryptionInfo: string): EncryptionInfo {\n // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\n return this.decode(base64url.decode(encryptionInfo))\n }\n\n public toBase64Url(): string {\n return base64url.encode(this.encode())\n }\n}\n","import {\n type CoseKey,\n 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 { UnsupportedDeviceMacAlgorithmError } from '../errors'\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 if (!this.namespaces.getDeviceNamespace(namespace)) {\n this.namespaces.setDeviceNamespace(namespace, DeviceSignedItems.create({ deviceSignedItems: new Map() }))\n }\n\n for (const [elementIdentifier, elementValue] of Object.entries(value)) {\n this.namespaces.setDeviceSignedElement(namespace, elementIdentifier, elementValue)\n }\n\n return this\n }\n\n public async sign(options: {\n signingKey: CoseKey\n algorithm: SignatureAlgorithm\n sessionTranscript: SessionTranscript\n }): Promise<DeviceSigned> {\n const protectedHeaders = ProtectedHeaders.create({\n protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.Algorithm, options.algorithm]]),\n })\n\n const unprotectedHeaders = UnprotectedHeaders.create({})\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 }): Promise<DeviceSigned> {\n // 18013-5 9.1.3.5: the device MAC shall use HMAC 256/256, which `DeviceAuth.verify` enforces.\n if (options.algorithm !== MacAlgorithm.HS256) {\n throw new UnsupportedDeviceMacAlgorithmError(\n `Device MAC algorithm must be HMAC 256/256 (${MacAlgorithm.HS256}), received ${options.algorithm}`\n )\n }\n\n const protectedHeaders = ProtectedHeaders.create({\n protectedHeaders: new Map<number, unknown>([[RegisteredCwtHeaderClaimKey.Algorithm, options.algorithm]]),\n })\n\n const unprotectedHeaders = UnprotectedHeaders.create({})\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 unprotectedHeaders.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 derivedKey = await deviceMac.createDeviceMacKey(\n {\n privateKey: options.privateKey,\n publicKey: options.publicKey,\n sessionTranscript: options.sessionTranscript,\n info: 'EMacKey',\n },\n this.ctx\n )\n\n const deviceMacWithTag = await deviceMac.authenticate(\n {\n key: derivedKey,\n algorithm: options.algorithm,\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","/**\n * The value of an `x5chain` COSE header (RFC 9360): a single certificate as a byte string, and a\n * chain of more than one certificate as an array, as in the examples of 18013-5 Annex D.\n */\nexport const x5chainHeaderValue = (certificateChain: Array<Uint8Array>): Uint8Array | Array<Uint8Array> =>\n certificateChain.length === 1 ? certificateChain[0] : certificateChain\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 { x5chainHeaderValue } from '../../utils/x5chain'\nimport {\n AtLeastOneCertificateRequiredError,\n DuplicateElementIdentifierError,\n InvalidValidityInfoError,\n MdlError,\n SignatureAlgorithmDoesNotMatchSigningKeyAlgorithmError,\n} 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 // Added to a copy, so that a call that throws leaves the namespace as it was.\n const issuerNamespace = [...(this.namespaces.getIssuerNamespace(namespace) ?? [])]\n\n const entries = values instanceof Map ? Array.from(values.entries()) : Object.entries(values)\n\n for (const [elementIdentifier, elementValue] of entries) {\n if (issuerNamespace.some((item) => item.elementIdentifier === elementIdentifier)) {\n throw new DuplicateElementIdentifierError(\n `Element '${elementIdentifier}' is already added to namespace '${namespace}'`\n )\n }\n\n // Digest IDs identify the digests of a namespace in the MSO, so they must be unique (9.1.2.4)\n const digestId = randomUnsignedInteger(this.ctx)\n if (issuerNamespace.some((item) => item.digestId === digestId)) {\n throw new MdlError(`Generated digest ID ${digestId} is already used in namespace '${namespace}'`)\n }\n\n issuerNamespace.push(\n IssuerSignedItem.fromOptions({\n digestId,\n random: this.ctx.crypto.random(32),\n elementIdentifier,\n elementValue,\n })\n )\n }\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 if (validityInfo.validFrom.getTime() < validityInfo.signed.getTime()) {\n throw new InvalidValidityInfoError(\n `validFrom (${validityInfo.validFrom.toISOString()}) must be equal to or later than signed (${validityInfo.signed.toISOString()})`\n )\n }\n\n if (validityInfo.validUntil.getTime() <= validityInfo.validFrom.getTime()) {\n throw new InvalidValidityInfoError(\n `validUntil (${validityInfo.validUntil.toISOString()}) must be later than validFrom (${validityInfo.validFrom.toISOString()})`\n )\n }\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, x5chainHeaderValue(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 { base64url } from '@owf/identity-common'\nimport type { MdocContext } from './context'\nimport {\n DeviceRequest,\n DeviceResponse,\n type DeviceResponseDocumentOptions,\n defaultVerificationCallback,\n IssuerSigned,\n type IssuerSignedVerificationResult,\n SessionTranscript,\n type VerificationCallback,\n} from './mdoc'\nimport { verifyAgeOverRequestLimit } from './utils/ageOver'\nimport {\n type HolderCredential,\n type HolderDeviceRequestMatchResult,\n matchCredentialsToDeviceRequest,\n} from './utils/matchDeviceRequest'\nimport { verifyVersion } from './utils/version'\n\n// biome-ignore lint/complexity/noStaticOnlyClass: part of the public API\nexport class Holder {\n /**\n * A string `issuerSigned` is base64url encoded, as OpenID4VCI defines it.\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. 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 * Without trust anchors the chain check of a request with reader auth\n * FAILS, unless `disableCertificateChainValidation` is set.\n */\n trustedCertificates?: Array<Uint8Array>\n /**\n * Only verify reader-auth signatures, without establishing trust in the\n * reader's certificate chain.\n */\n disableCertificateChainValidation?: boolean\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 = SessionTranscript.from(options.sessionTranscript)\n\n const onCheck = options.verificationCallback ?? defaultVerificationCallback\n verifyVersion({ structure: 'Device Request', version: deviceRequest.version }, onCheck)\n verifyAgeOverRequestLimit(deviceRequest, onCheck)\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 disableCertificateChainValidation: options.disableCertificateChainValidation,\n now: options.now,\n },\n ctx\n )\n }\n }\n\n /**\n * Match the credentials of the holder against a device request, to select which credentials can\n * answer which doc request. See {@link matchCredentialsToDeviceRequest} for what is matched.\n *\n * `createDeviceResponseForDeviceRequest` selects the elements to disclose the same way, so a\n * credential that matches can answer the doc request with the same `deviceNamespaces`.\n */\n public static matchDeviceRequest(options: {\n deviceRequest: Uint8Array | DeviceRequest\n credentials: Array<IssuerSigned | HolderCredential>\n /**\n * See `DeviceRequestMatchOptions.treatAmbiguousMultipleDocRequestsAsAlternatives`. Defaults to\n * `false`.\n */\n treatAmbiguousMultipleDocRequestsAsAlternatives?: boolean\n }): HolderDeviceRequestMatchResult {\n return matchCredentialsToDeviceRequest({\n deviceRequest:\n options.deviceRequest instanceof DeviceRequest\n ? options.deviceRequest\n : DeviceRequest.decode(options.deviceRequest),\n credentials: options.credentials,\n treatAmbiguousMultipleDocRequestsAsAlternatives: options.treatAmbiguousMultipleDocRequestsAsAlternatives,\n })\n }\n\n public static async createDeviceResponseForDeviceRequest(\n options: {\n deviceRequest: DeviceRequest\n sessionTranscript: SessionTranscript | Uint8Array\n documents: Array<DeviceResponseDocumentOptions>\n },\n context: Pick<MdocContext, 'cose' | 'crypto'>\n ) {\n return await DeviceResponse.createWithDeviceRequest(options, context)\n }\n}\n","import {\n type CoseKey,\n Curve,\n KeyType,\n ProtectedHeaders,\n RegisteredCwtHeaderClaimKey,\n UnprotectedHeaders,\n} from '@owf/cose'\nimport { base64url } from '@owf/identity-common'\nimport { z } from 'zod'\nimport { HpkeSuiteId, type MdocContext } from './context'\nimport {\n DeviceRequest,\n DeviceResponse,\n type DeviceResponseDocumentOptions,\n type DeviceResponseVerificationResult,\n DocRequest,\n defaultVerificationCallback,\n EncryptedResponse,\n EncryptedResponseData,\n EncryptionInfo,\n EncryptionParameters,\n HpkeNotSupportedError,\n InvalidDcApiRequestError,\n InvalidDcApiResponseError,\n InvalidEncryptionInfoError,\n InvalidOriginError,\n ItemsRequest,\n MissingOriginError,\n ReaderAuth,\n ReaderAuthentication,\n SessionTranscript,\n type VerificationCallback,\n} from './mdoc'\nimport { verifyAgeOverRequestLimit } from './utils/ageOver'\nimport type { DeviceRequestMatchOptions } from './utils/matchDeviceRequest'\nimport { verifyVersion } from './utils/version'\nimport { x5chainHeaderValue } from './utils/x5chain'\n\n/**\n * DC API protocol identifier for ISO/IEC TS 18013-7:2025 Annex C.\n */\nexport const isoMdocDcApiProtocol = 'org-iso-mdoc'\n\n/**\n * The only HPKE suite Annex C allows (C.4).\n */\nexport const isoMdocDcApiHpkeSuite = HpkeSuiteId.DhkemP256HkdfSha256HkdfSha256Aes128Gcm\n\n/**\n * Minimum nonce entropy required by C.2.\n */\nconst minimumNonceLength = 16\n\n/**\n * Base64url-no-pad, as Annex C encodes every member of the request and response payloads.\n */\nconst base64UrlSchema = z.base64url().min(1)\n\n/**\n * Request payload exchanged over the DC API (C.2). Both members are base64url-no-pad encoded CBOR.\n */\nexport const isoMdocDcApiRequestSchema = z.object({\n deviceRequest: base64UrlSchema,\n encryptionInfo: base64UrlSchema,\n})\nexport type IsoMdocDcApiRequest = z.infer<typeof isoMdocDcApiRequestSchema>\n\n/**\n * Response payload returned over the DC API (C.3), base64url-no-pad encoded CBOR.\n */\nexport const isoMdocDcApiResponseSchema = z.object({\n response: base64UrlSchema,\n})\nexport type IsoMdocDcApiResponse = z.infer<typeof isoMdocDcApiResponseSchema>\n\n/**\n * The response as it may be handed to {@link IsoMdocDcApi.decryptResponse}, normalized to the\n * base64url `response` string.\n */\nconst isoMdocDcApiResponseInputSchema = z.union([\n base64UrlSchema,\n isoMdocDcApiResponseSchema.transform(({ response }) => response),\n])\n\nexport type IsoMdocDcApiParsedDocRequest = {\n docRequest: DocRequest\n docType: string\n namespaces: Map<string, Map<string, boolean>>\n /**\n * Whether the doc request carries reader auth, which is optional in Annex C. This does not say\n * whether reader auth is valid: an invalid signature or an untrusted certificate chain surfaces\n * through the verification callback.\n */\n hasReaderAuth: boolean\n readerCertificateChain?: Array<Uint8Array>\n}\n\nexport type IsoMdocDcApiParsedRequest = {\n origin: string\n deviceRequest: DeviceRequest\n encryptionInfo: EncryptionInfo\n encryptionInfoBase64Url: string\n sessionTranscript: SessionTranscript\n docRequests: Array<IsoMdocDcApiParsedDocRequest>\n}\n\nexport type IsoMdocDcApiCreatedRequest = {\n request: IsoMdocDcApiRequest\n deviceRequest: DeviceRequest\n encryptionInfo: EncryptionInfo\n sessionTranscript?: SessionTranscript\n}\n\n/**\n * ISO/IEC TS 18013-7:2025 Annex C (`org-iso-mdoc`) request and response handling.\n *\n * The HPKE operations are provided by the caller through `ctx.crypto.hpke`, so this package stays\n * free of a cryptographic backend.\n */\n// biome-ignore lint/complexity/noStaticOnlyClass: part of the public API\nexport class IsoMdocDcApi {\n /**\n * Build an Annex C request (verifier side).\n *\n * When `readerAuth` is provided each doc request is signed over a `ReaderAuthentication`\n * structure that binds the session transcript, and therefore a single `origin` — a signed request\n * can only be used against the origin it was created for.\n */\n public static async createRequest(\n options: {\n docRequests: Array<{\n docType: string\n namespaces: Record<string, Record<string, boolean>> | Map<string, Map<string, boolean>>\n }>\n /**\n * Public key the response is encrypted to. Must be an EC P-256 key.\n */\n recipientPublicKey: CoseKey\n /**\n * At least 16 bytes of entropy, fresh per transaction (C.2). Generated when omitted.\n */\n nonce?: Uint8Array\n version?: string\n readerAuth?: {\n signingKey: CoseKey\n certificateChain: Array<Uint8Array>\n origin: string\n }\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose'>\n ): Promise<IsoMdocDcApiCreatedRequest> {\n const nonce = options.nonce ?? ctx.crypto.random(minimumNonceLength)\n if (nonce.length < minimumNonceLength) {\n throw new InvalidEncryptionInfoError(`Nonce must be at least ${minimumNonceLength} bytes`)\n }\n assertP256PublicKey(options.recipientPublicKey)\n if (options.readerAuth) assertSerializedOrigin(options.readerAuth.origin)\n\n const encryptionInfo = EncryptionInfo.create({\n encryptionParameters: EncryptionParameters.create({ nonce, recipientPublicKey: options.recipientPublicKey }),\n })\n const encryptionInfoBase64Url = encryptionInfo.toBase64Url()\n\n // The transcript only depends on the encryption info and the origin, so it can be computed\n // before the doc requests are signed.\n const sessionTranscript = options.readerAuth\n ? await SessionTranscript.forIsoMdocDcApi({ encryptionInfoBase64Url, origin: options.readerAuth.origin }, ctx)\n : undefined\n\n const docRequests = await Promise.all(\n options.docRequests.map(async ({ docType, namespaces }) => {\n const itemsRequest = ItemsRequest.create({ docType, namespaces })\n\n if (!options.readerAuth || !sessionTranscript) {\n return DocRequest.create({ itemsRequest })\n }\n\n const { signingKey, certificateChain } = options.readerAuth\n const unprotectedHeaders = UnprotectedHeaders.create({})\n unprotectedHeaders.headers?.set(RegisteredCwtHeaderClaimKey.X5Chain, x5chainHeaderValue(certificateChain))\n\n const readerAuth = (await ReaderAuth.create({\n protectedHeaders: ProtectedHeaders.create({\n protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.Algorithm, signingKey.algorithm]]),\n }),\n unprotectedHeaders,\n payload: null,\n }).sign(\n {\n signingKey,\n detachedPayload: ReaderAuthentication.create({ sessionTranscript, itemsRequest }).encode({\n asDataItem: true,\n }),\n },\n { sign: ctx.cose.sign1.sign }\n )) as ReaderAuth\n\n return DocRequest.create({ itemsRequest, readerAuth })\n })\n )\n\n const deviceRequest = DeviceRequest.create({ version: options.version, docRequests })\n\n return {\n request: {\n deviceRequest: base64url.encode(deviceRequest.encode()),\n encryptionInfo: encryptionInfoBase64Url,\n },\n deviceRequest,\n encryptionInfo,\n sessionTranscript,\n }\n }\n\n /**\n * Parse and validate an Annex C request (wallet side), and verify reader auth where present.\n *\n * `origin` must be the origin the platform provided; C.5 requires the mdoc to abort when no\n * origin was received.\n */\n public static async parseRequest(\n options: {\n request: IsoMdocDcApiRequest\n origin: string | undefined\n /**\n * Trust anchors for reader certificate chains. Without trust anchors the chain check of a doc\n * request with reader auth FAILS, unless `disableReaderCertificateChainValidation` is set.\n */\n trustedReaderCertificates?: Array<Uint8Array>\n /**\n * Only verify reader signatures, without establishing trust in the reader certificate chains.\n */\n disableReaderCertificateChainValidation?: boolean\n verificationCallback?: VerificationCallback\n now?: Date\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose' | 'x509'>\n ): Promise<IsoMdocDcApiParsedRequest> {\n const { origin } = options\n if (!origin) throw new MissingOriginError('No origin was provided by the DC API')\n assertSerializedOrigin(origin)\n\n // The request is handed to us by the platform, so validate its shape before decoding anything.\n const request = parseOrThrow(isoMdocDcApiRequestSchema, options.request, InvalidDcApiRequestError, 'DC API request')\n\n const encryptionInfoBase64Url = request.encryptionInfo\n const encryptionInfo = decodeOrThrow(\n () => EncryptionInfo.fromBase64Url(encryptionInfoBase64Url),\n InvalidDcApiRequestError,\n 'encryption info'\n )\n\n if (encryptionInfo.nonce.length < minimumNonceLength) {\n throw new InvalidEncryptionInfoError(`Nonce must be at least ${minimumNonceLength} bytes`)\n }\n assertP256PublicKey(encryptionInfo.recipientPublicKey)\n\n const deviceRequest = decodeOrThrow(\n () => DeviceRequest.decode(base64url.decode(request.deviceRequest)),\n InvalidDcApiRequestError,\n 'device request'\n )\n const onCheck = options.verificationCallback ?? defaultVerificationCallback\n verifyVersion({ structure: 'Device Request', version: deviceRequest.version }, onCheck)\n verifyAgeOverRequestLimit(deviceRequest, onCheck)\n\n const sessionTranscript = await SessionTranscript.forIsoMdocDcApi({ encryptionInfoBase64Url, origin }, ctx)\n\n const docRequests: Array<IsoMdocDcApiParsedDocRequest> = []\n for (const docRequest of deviceRequest.docRequests) {\n const { readerAuth } = docRequest\n\n if (readerAuth) {\n await readerAuth.verify(\n {\n readerAuthentication: { itemsRequest: docRequest.itemsRequest, sessionTranscript },\n verificationCallback: options.verificationCallback,\n trustedCertificates: options.trustedReaderCertificates,\n disableCertificateChainValidation: options.disableReaderCertificateChainValidation,\n now: options.now,\n },\n ctx\n )\n }\n\n docRequests.push({\n docRequest,\n docType: docRequest.itemsRequest.docType,\n namespaces: docRequest.itemsRequest.namespaces,\n hasReaderAuth: !!readerAuth,\n readerCertificateChain: readerAuth?.certificateChain,\n })\n }\n\n return {\n origin,\n deviceRequest,\n encryptionInfo,\n encryptionInfoBase64Url,\n sessionTranscript,\n docRequests,\n }\n }\n\n /**\n * Create the encrypted Annex C response (wallet side).\n *\n * Device auth uses `deviceSignature`; the MAC variant has no key-agreement channel in the DC API\n * flow.\n */\n public static async createResponse(\n options: {\n parsedRequest: IsoMdocDcApiParsedRequest\n /**\n * The documents to disclose, each naming the doc request of `parsedRequest.docRequests` it\n * answers through `docRequestIndex`. See `DeviceResponse.createWithDeviceRequest` for how the\n * elements to disclose are selected.\n */\n documents: Array<\n Pick<DeviceResponseDocumentOptions, 'issuerSigned' | 'docRequestIndex' | 'elements' | 'deviceNamespaces'> & {\n deviceKey: CoseKey\n }\n >\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose'>\n ): Promise<IsoMdocDcApiResponse> {\n const hpke = assertHpke(ctx)\n const { parsedRequest } = options\n\n const deviceResponse = await DeviceResponse.createWithDeviceRequest(\n {\n deviceRequest: parsedRequest.deviceRequest,\n sessionTranscript: parsedRequest.sessionTranscript,\n documents: options.documents.map((document) => ({\n docRequestIndex: document.docRequestIndex,\n issuerSigned: document.issuerSigned,\n elements: document.elements,\n deviceNamespaces: document.deviceNamespaces,\n signature: { signingKey: document.deviceKey },\n })),\n },\n ctx\n )\n\n const { enc, ciphertext } = await hpke.seal({\n suite: isoMdocDcApiHpkeSuite,\n recipientPublicKey: parsedRequest.encryptionInfo.recipientPublicKey,\n // C.4: `info` is the session transcript encoded as a bare CBOR array, not as\n // SessionTranscriptBytes (tag 24). `aad` is empty.\n info: parsedRequest.sessionTranscript.encode(),\n plaintext: deviceResponse.encode(),\n })\n\n const encryptedResponse = EncryptedResponse.create({\n encryptedResponseData: EncryptedResponseData.create({ enc, ciphertext }),\n })\n\n return { response: encryptedResponse.toBase64Url() }\n }\n\n /**\n * Decrypt an Annex C response (verifier side) without verifying the documents.\n *\n * Decryption is bound to the origin through the session transcript, so a response relayed from a\n * different origin fails here.\n */\n public static async decryptResponse(\n options: {\n response: IsoMdocDcApiResponse | string\n origin: string\n /**\n * The base64url `encryptionInfo` exactly as it was sent to the wallet.\n */\n encryptionInfo: string\n /**\n * The recipient key whose public part was sent to the wallet in `encryptionInfo`. When the\n * private key is held by a key management system, pass the public key carrying the `keyId`\n * the `ctx.crypto.hpke.open` implementation resolves the private key with.\n */\n recipientKey: CoseKey\n },\n ctx: Pick<MdocContext, 'crypto'>\n ): Promise<{ deviceResponse: DeviceResponse; sessionTranscript: SessionTranscript }> {\n const hpke = assertHpke(ctx)\n if (!options.origin) throw new MissingOriginError('No origin was provided by the DC API')\n assertSerializedOrigin(options.origin)\n\n // The response comes from the wallet, so validate its shape before decoding anything.\n const response = parseOrThrow(\n isoMdocDcApiResponseInputSchema,\n options.response,\n InvalidDcApiResponseError,\n 'DC API response'\n )\n\n const encryptedResponse = decodeOrThrow(\n () => EncryptedResponse.fromBase64Url(response),\n InvalidDcApiResponseError,\n 'encrypted response'\n )\n\n const sessionTranscript = await SessionTranscript.forIsoMdocDcApi(\n { encryptionInfoBase64Url: options.encryptionInfo, origin: options.origin },\n ctx\n )\n\n const plaintext = await hpke.open({\n suite: isoMdocDcApiHpkeSuite,\n recipientKey: options.recipientKey,\n enc: encryptedResponse.enc,\n info: sessionTranscript.encode(),\n ciphertext: encryptedResponse.ciphertext,\n })\n\n const deviceResponse = decodeOrThrow(\n () => DeviceResponse.decode(plaintext),\n InvalidDcApiResponseError,\n 'device response'\n )\n\n return { deviceResponse, sessionTranscript }\n }\n\n /**\n * Decrypt and verify an Annex C response (verifier side).\n */\n public static async verifyResponse(\n options: {\n response: IsoMdocDcApiResponse | string\n origin: string\n encryptionInfo: string\n recipientKey: CoseKey\n deviceRequest?: DeviceRequest\n deviceRequestMatchOptions?: DeviceRequestMatchOptions\n trustedCertificates: Array<{ issuance: Array<Uint8Array>; status?: Array<Uint8Array> }>\n disableCertificateChainValidation?: boolean\n disableStatusValidation?: boolean\n onCheck?: VerificationCallback\n now?: Date\n skewSeconds?: number\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose' | 'x509' | 'fetch'>\n ): Promise<{\n deviceResponse: DeviceResponse\n verificationResult: DeviceResponseVerificationResult\n }> {\n const { deviceResponse, sessionTranscript } = await IsoMdocDcApi.decryptResponse(options, ctx)\n\n const verificationResult = await deviceResponse.verify(\n {\n deviceRequest: options.deviceRequest,\n deviceRequestMatchOptions: options.deviceRequestMatchOptions,\n sessionTranscript,\n trustedCertificates: options.trustedCertificates,\n disableCertificateChainValidation: options.disableCertificateChainValidation,\n disableStatusValidation: options.disableStatusValidation,\n onCheck: options.onCheck,\n now: options.now,\n skewSeconds: options.skewSeconds,\n },\n ctx\n )\n\n return { deviceResponse, verificationResult }\n }\n}\n\nfunction assertHpke(ctx: Pick<MdocContext, 'crypto'>) {\n const { hpke } = ctx.crypto\n if (!hpke) {\n throw new HpkeNotSupportedError('The mdoc context does not provide HPKE support')\n }\n\n if (!hpke.suites.includes(isoMdocDcApiHpkeSuite)) {\n throw new HpkeNotSupportedError(`The mdoc context does not support HPKE suite '${isoMdocDcApiHpkeSuite}'`)\n }\n\n return hpke\n}\n\nfunction assertP256PublicKey(coseKey: CoseKey) {\n if (coseKey.keyType !== KeyType.Ec || coseKey.curve !== Curve['P-256']) {\n throw new InvalidEncryptionInfoError('Recipient public key must be an EC P-256 key')\n }\n}\n\n/**\n * The origin must be an ASCII serialized origin, as the DC API provides it (C.5), for instance\n * `https://verifier.example.com`. The session transcript binds the exact string, so for instance a\n * trailing slash would silently produce a transcript the other party does not compute.\n */\nfunction assertSerializedOrigin(origin: string) {\n let serializedOrigin: string | undefined\n try {\n serializedOrigin = new URL(origin).origin\n } catch {\n serializedOrigin = undefined\n }\n\n if (serializedOrigin === undefined || serializedOrigin === 'null' || serializedOrigin !== origin) {\n throw new InvalidOriginError(\n serializedOrigin && serializedOrigin !== 'null'\n ? `Origin '${origin}' is not a serialized origin, did you mean '${serializedOrigin}'?`\n : `Origin '${origin}' is not a serialized origin`\n )\n }\n}\n\n/**\n * Decode untrusted CBOR, surfacing a decoding failure as the DC API error for that payload.\n */\nfunction decodeOrThrow<Decoded>(\n decode: () => Decoded,\n ErrorClass: new (message: string) => Error,\n description: string\n): Decoded {\n try {\n return decode()\n } catch (error) {\n throw new ErrorClass(`Invalid ${description}: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\n/**\n * Parse untrusted input, surfacing a validation failure as the DC API error for that payload.\n */\nfunction parseOrThrow<Schema extends z.ZodType>(\n schema: Schema,\n data: unknown,\n ErrorClass: new (message: string) => Error,\n description: string\n): z.output<Schema> {\n const result = schema.safeParse(data)\n if (!result.success) {\n throw new ErrorClass(`Invalid ${description}: ${z.prettifyError(result.error)}`)\n }\n\n return result.data\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 DeviceRequest,\n DeviceResponse,\n type DeviceResponseVerificationResult,\n type SessionTranscript,\n} from './mdoc/index.js'\nimport {\n type DeviceRequestMatchOptions,\n type DeviceRequestMatchResult,\n matchDeviceRequest,\n} from './utils/matchDeviceRequest.js'\n\n// biome-ignore lint/complexity/noStaticOnlyClass: part of the public API\nexport class Verifier {\n public static async verifyDeviceResponse(\n options: {\n deviceRequest?: DeviceRequest\n deviceRequestMatchOptions?: DeviceRequestMatchOptions\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 : DeviceResponse.decode(options.deviceResponse)\n\n return deviceResponse.verify(options, ctx)\n }\n\n /**\n * Match a device response against the device request it answers, without verifying it. See\n * {@link matchDeviceRequest} for what is matched.\n *\n * `Verifier.verifyDeviceResponse` runs the same match as part of verification when a\n * `deviceRequest` is passed, reporting it through `onCheck` and returning it as\n * `deviceRequestMatch`.\n */\n public static matchDeviceRequest(options: {\n deviceRequest: Uint8Array | DeviceRequest\n deviceResponse: Uint8Array | DeviceResponse\n matchOptions?: DeviceRequestMatchOptions\n }): DeviceRequestMatchResult {\n return matchDeviceRequest({\n matchOptions: options.matchOptions,\n deviceRequest:\n options.deviceRequest instanceof DeviceRequest\n ? options.deviceRequest\n : DeviceRequest.decode(options.deviceRequest),\n deviceResponse:\n options.deviceResponse instanceof DeviceResponse\n ? options.deviceResponse\n : DeviceResponse.decode(options.deviceResponse),\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;AAWA,IAAY,cAAL,yBAAA,a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AK,IAAI,KAAK;GAAE,GAAG;GAAS;EAAW,CAAC;CACvD;AACF;;;AC3BA,IAAa,WAAb,MAAsB;CACpB,aAAoB,qBAClB,SAaA,KAC2C;EAM3C,QAJE,QAAQ,0BAA0B,iBAC9B,QAAQ,iBACR,eAAe,OAAO,QAAQ,cAAc,EAAA,CAE5B,OAAO,SAAS,GAAG;CAC3C;;;;;;;;;CAUA,OAAc,mBAAmB,SAIJ;EAC3B,OAAO,mBAAmB;GACxB,cAAc,QAAQ;GACtB,eACE,QAAQ,yBAAyB,gBAC7B,QAAQ,gBACR,cAAc,OAAO,QAAQ,aAAa;GAChD,gBACE,QAAQ,0BAA0B,iBAC9B,QAAQ,iBACR,eAAe,OAAO,QAAQ,cAAc;EACpD,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["z","cborDecode","cborEncode","z","z","z","z","z","CoseKey","z","z","z","z","z","CoseKey","cborEncode","cborEncode","cborEncode","z","z","Mac0","Sign1","z","CoseKey","z","z","z","z","z","Sign1","z","z","z","z","StatusListInfo","z","z","z","RegisteredCwtHeaderClaimKey","ProtectedHeaders","z","RegisteredCwtClaimKey","ProtectedHeaders","RegisteredCwtHeaderClaimKey","RegisteredCwtHeaderClaimKey","RegisteredCwtClaimKey","Sign1","cborDecode","z","z","z","z","z","z","UnprotectedHeaders","RegisteredCwtHeaderClaimKey","ProtectedHeaders","z","z","CoseKey","z","ProtectedHeaders","RegisteredCwtHeaderClaimKey","UnprotectedHeaders","ProtectedHeaders","RegisteredCwtHeaderClaimKey","UnprotectedHeaders","z","UnprotectedHeaders","RegisteredCwtHeaderClaimKey","ProtectedHeaders","KeyType","Curve","CoseKey"],"sources":["../src/context.ts","../src/mdoc/errors.ts","../src/mdoc/models/ble-options.ts","../src/utils/keyAuthorizations.ts","../src/mdoc/check-callback.ts","../src/utils/cbor.ts","../src/mdoc/original-bytes-cbor-structure.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/engagement-to-app-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/utils/ageOver.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/getOwnProperty.ts","../src/utils/version.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/identifier-list-cwt-headers.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/mso-revocation-list.ts","../src/mdoc/models/issuer-auth.ts","../src/mdoc/models/issuer-signed-item.ts","../src/mdoc/models/issuer-namespaces.ts","../src/mdoc/models/issuer-signed.ts","../src/utils/matchDeviceRequest.ts","../src/mdoc/models/device-signed.ts","../src/mdoc/models/error-items.ts","../src/mdoc/models/errors.ts","../src/mdoc/models/document.ts","../src/mdoc/models/document-error.ts","../src/mdoc/models/device-response.ts","../src/mdoc/models/encrypted-response-data.ts","../src/mdoc/models/encrypted-response.ts","../src/mdoc/models/encryption-parameters.ts","../src/mdoc/models/encryption-info.ts","../src/mdoc/builders/device-signed-builder.ts","../src/utils/randomUnsignedInteger.ts","../src/utils/x5chain.ts","../src/mdoc/builders/issuer-signed-builder.ts","../src/holder.ts","../src/iso-mdoc-dc-api.ts","../src/issuer.ts","../src/verifier.ts"],"sourcesContent":["import type { CoseKey, DigestAlgorithm, Mac0Context, MacAlgorithm, Sign1Context, SignatureAlgorithm } from '@owf/cose'\n\ntype MaybePromise<T> = Promise<T> | T\n\n/**\n * HPKE (RFC 9180) cipher suites, identified as `<kem>/<kdf>/<aead>`.\n *\n * ISO/IEC TS 18013-7:2025 C.4 fixes the DC API suite to\n * {@link HpkeSuiteId.DhkemP256HkdfSha256HkdfSha256Aes128Gcm}; the other members exist so the same\n * callbacks can be reused by protocols that negotiate a suite.\n */\nexport enum HpkeSuiteId {\n /** DHKEM(P-256, HKDF-SHA256) / HKDF-SHA256 / AES-128-GCM. */\n DhkemP256HkdfSha256HkdfSha256Aes128Gcm = 'dhkem-p256-hkdf-sha256/hkdf-sha256/aes-128-gcm',\n\n /** DHKEM(P-256, HKDF-SHA256) / HKDF-SHA256 / AES-256-GCM. */\n DhkemP256HkdfSha256HkdfSha256Aes256Gcm = 'dhkem-p256-hkdf-sha256/hkdf-sha256/aes-256-gcm',\n\n /** DHKEM(X25519, HKDF-SHA256) / HKDF-SHA256 / AES-128-GCM. */\n DhkemX25519HkdfSha256HkdfSha256Aes128Gcm = 'dhkem-x25519-hkdf-sha256/hkdf-sha256/aes-128-gcm',\n}\n\nexport interface HpkeContext {\n /**\n * Suites the `seal` and `open` implementations support. Callers check this before use so an\n * unsupported suite surfaces as a protocol error instead of a callback failure.\n */\n suites: Array<HpkeSuiteId>\n\n /**\n * Single-shot HPKE seal in base mode (RFC 9180 §6.1).\n */\n seal: (input: {\n suite: HpkeSuiteId\n recipientPublicKey: CoseKey\n info: Uint8Array\n aad?: Uint8Array\n plaintext: Uint8Array\n }) => MaybePromise<{ enc: Uint8Array; ciphertext: Uint8Array }>\n\n /**\n * Single-shot HPKE open in base mode (RFC 9180 §6.1). `enc` is the raw serialized encapsulated\n * key for the suite's KEM (uncompressed SEC1 point for the DHKEM(P-256) suites).\n */\n open: (input: {\n suite: HpkeSuiteId\n /**\n * The recipient key. Implementations that keep private keys inside a key management system are\n * passed the public key and resolve the associated private key based on its `keyId`, the same\n * way {@link Sign1Context.sign} resolves a signing key.\n */\n recipientKey: CoseKey\n enc: Uint8Array\n info: Uint8Array\n aad?: Uint8Array\n ciphertext: Uint8Array\n }) => MaybePromise<Uint8Array>\n}\n\nexport interface MdocContext {\n fetch: typeof fetch\n crypto: {\n random: (length: number) => Uint8Array\n digest: (input: { digestAlgorithm: DigestAlgorithm; bytes: Uint8Array }) => MaybePromise<Uint8Array>\n hdkf: (input: {\n digestAlgorithm?: DigestAlgorithm\n privateKey: Uint8Array\n publicKey: Uint8Array\n salt: Uint8Array\n info: Uint8Array\n }) => MaybePromise<Uint8Array>\n\n /**\n * Required for the ISO 18013-7 Annex C (`org-iso-mdoc`) DC API flows only.\n */\n hpke?: HpkeContext\n }\n\n cose: {\n sign1: {\n sign: Sign1Context['sign']\n verify: Sign1Context['verify']\n }\n\n mac0: Mac0Context\n }\n\n x509: {\n /**\n * The values of a field of the subject distinguished name of a certificate, e.g. `C` or `ST`.\n */\n getSubjectNameField: (options: { certificate: Uint8Array; field: string }) => string[]\n getPublicKey: (options: {\n certificate: Uint8Array\n algorithm?: SignatureAlgorithm | MacAlgorithm\n }) => Promise<CoseKey>\n\n /**\n * Verify a X.509 certificate chain, returning it with the leaf first and the trusted root last.\n */\n verifyCertificateChain: (input: {\n trustedCertificates: Uint8Array[]\n x5chain: Uint8Array[]\n now?: Date\n }) => MaybePromise<{ chain: Uint8Array[] }>\n\n getCertificateData: (input: { certificate: Uint8Array }) => MaybePromise<{\n issuerName: string\n subjectName: string\n serialNumber: string\n thumbprint: string\n notBefore: Date\n notAfter: Date\n pem: string\n }>\n }\n}\n","import type { VerificationAssessment, VerificationCallback } from './check-callback.js'\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 {}\n\n/**\n * ISO/IEC 18013-5 9.1.3.4 forbids an mdoc from authenticating device-signed elements its device key\n * is not authorized for in the MSO's `KeyAuthorizations`. Creating such a response would produce\n * one every conformant mdoc reader has to reject, so it is refused up front.\n */\nexport class DeviceKeyNotAuthorizedError extends MdlError {}\n\n/**\n * An element to disclose in a device response is requested, but the document cannot disclose it:\n * the issuer did not sign it, and no device-signed value the device key is authorized for was\n * provided.\n */\nexport class MissingRequestedElementError extends MdlError {}\n\n/**\n * The elements selected for disclosure in a device response do not fit the doc request: an element\n * is selected that the doc request does not ask for, or a selected element is answered with the same\n * age attestation as a requested element that is left out.\n */\nexport class InvalidElementSelectionError extends MdlError {}\n\n/**\n * A credential is used to answer a doc request for another docType: the docType of its mobile\n * security object is not the docType the doc request asks for.\n */\nexport class DocTypeMismatchError extends MdlError {}\n\n/**\n * ISO/IEC 18013-5 7.2.5: \"an mDL reader shall not request more than two age_over_NN data elements\".\n * Thrown when creating an items request that asks for more than two in a namespace, and when a\n * device response would disclose more than two in a namespace, as together they narrow down the age\n * of the holder.\n */\nexport class AgeOverLimitExceededError extends MdlError {}\n\n/**\n * The options to match a device request with do not fit the device request: they refer to a doc\n * request the device request does not have, or to the same doc request more than once.\n */\nexport class InvalidDeviceRequestMatchOptionsError extends MdlError {}\nexport class AtLeastOneCertificateRequiredError extends MdlError {}\n\n/**\n * ISO/IEC 18013-5 8.3.2.1.2.2: a namespace must not have two or more elements with the same element\n * identifier.\n */\nexport class DuplicateElementIdentifierError extends MdlError {}\n\n/**\n * ISO/IEC 18013-5 9.1.2.4: \"The validFrom element shall be equal or later than the signed element\",\n * and \"the validUntil element shall be later than the validFrom element\".\n */\nexport class InvalidValidityInfoError extends MdlError {}\n\n/**\n * ISO/IEC 18013-5 9.1.3.5: the device MAC shall use HMAC 256/256.\n */\nexport class UnsupportedDeviceMacAlgorithmError extends MdlError {}\nexport class SignatureAlgorithmDoesNotMatchSigningKeyAlgorithmError extends MdlError {}\nexport class UnableToExtractX5ChainFromCwtError extends MdlError {}\nexport class NoPublicKeySetOnStatusListError extends MdlError {}\nexport class InvalidSignatureError extends MdlError {}\n\n/**\n * ISO/IEC 18013-5 second edition § 12.3.6.3 requires the status list of an MSO to be a Status List\n * Token in CWT format, \"since the IssuerAuth structure is a CWT\". A list served as a JWT is a\n * deviation, and is rejected rather than verified.\n */\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\n/**\n * An MSO revocation list — status list or identifier list — was well-formed and correctly\n * signed, but one of the claim requirements from ISO/IEC 18013-5 second edition 12.3.6 /\n * the Token Status List specification was not met (missing or mismatched subject, missing\n * or passed expiration, or an issuance time in the future).\n */\nexport class InvalidRevocationListError extends MdlError {}\n\n/**\n * ISO/IEC TS 18013-7:2025 C.5 requires the mdoc to abort when the DC API did not provide an origin,\n * as the session transcript — and thus the anti-relay binding — cannot be computed without it.\n */\nexport class MissingOriginError extends MdlError {}\n\n/**\n * The origin is not an origin as the DC API provides it: the ASCII serialization of an origin\n * (`scheme://host[:port]`), without a path, a trailing slash or a default port. The session transcript\n * binds the exact origin, so any other form would not match the origin the other party uses.\n */\nexport class InvalidOriginError extends MdlError {}\nexport class HpkeNotSupportedError extends MdlError {}\n\n/**\n * The request or response payload handed over the DC API did not have the shape Annex C defines.\n */\nexport class InvalidDcApiRequestError extends MdlError {}\nexport class InvalidDcApiResponseError extends MdlError {}\nexport class InvalidEncryptionInfoError extends MdlError {}\nexport class InvalidEncryptedResponseError extends MdlError {}\n\n/**\n * A verification check failed.\n *\n * Verification reports every check it runs through a {@link VerificationCallback}; the default\n * callback turns the first `FAILED` check into this error. `assessment` is that check, including\n * the structured `result` of the checks that produce one, so that a caller which does not collect\n * the checks itself does not have to parse the message to learn what failed.\n */\nexport class VerificationError extends MdlError {\n public readonly assessment: VerificationAssessment\n\n public constructor(message: string, assessment: VerificationAssessment) {\n super(message)\n this.assessment = assessment\n }\n}\n","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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\n return this.fromEncodedStructure(map)\n }\n}\n","import type { DataElementIdentifier } from '../mdoc/models/data-element-identifier'\nimport type { DeviceNamespaces } from '../mdoc/models/device-namespaces'\nimport type { KeyAuthorizations } from '../mdoc/models/key-authorizations'\nimport type { Namespace } from '../mdoc/models/namespace'\n\nexport type DeviceSignedElement = {\n namespace: Namespace\n elementIdentifier: DataElementIdentifier\n}\n\n/**\n * The data elements the mdoc authenticated through `DeviceNameSpaces`, flattened across namespaces.\n */\nexport const collectDeviceSignedElements = (deviceNamespaces?: DeviceNamespaces): Array<DeviceSignedElement> =>\n Array.from(deviceNamespaces?.deviceNamespaces ?? []).flatMap(([namespace, deviceSignedItems]) =>\n Array.from(deviceSignedItems.deviceSignedItems.keys()).map((elementIdentifier) => ({\n namespace,\n elementIdentifier,\n }))\n )\n\n/**\n * Whether the device key is authorized to authenticate a device-signed element, either for its\n * whole namespace or for the data element itself (18013-5 9.1.2.4).\n */\nexport const isDeviceSignedElementAuthorized = (\n keyAuthorizations: KeyAuthorizations | undefined,\n { namespace, elementIdentifier }: DeviceSignedElement\n) =>\n (keyAuthorizations?.namespaces?.includes(namespace) ||\n keyAuthorizations?.dataElements?.get(namespace)?.includes(elementIdentifier)) ??\n false\n\n/**\n * The device-signed elements the device key is not authorized to authenticate.\n *\n * ISO/IEC 18013-5 9.1.3.4: \"An mdoc shall only authenticate response data elements in\n * `DeviceNameSpaces` if the key it is using for mdoc authentication is authorized to authenticate\n * these elements in the `KeyAuthorizations` structure in the MSO. The mdoc reader shall validate\n * this authorization as part of validating the mdoc authentication.\" Authorization is given either\n * for a whole namespace or per data element (9.1.2.4), so both sides run this: the mdoc before it\n * signs or MACs a response, the mdoc reader after it decodes one.\n */\nexport const findUnauthorizedDeviceSignedElements = (options: {\n deviceNamespaces?: DeviceNamespaces\n keyAuthorizations?: KeyAuthorizations\n}): Array<DeviceSignedElement> =>\n collectDeviceSignedElements(options.deviceNamespaces).filter(\n (element) => !isDeviceSignedElementAuthorized(options.keyAuthorizations, element)\n )\n\n/**\n * A shared description of unauthorized elements, so the mdoc's error and the mdoc reader's failed\n * check name the same elements in the same way.\n */\nexport const describeUnauthorizedDeviceSignedElements = (unauthorized: Array<DeviceSignedElement>) =>\n `The device key is not authorized to authenticate ${unauthorized\n .map(({ namespace, elementIdentifier }) => `'${elementIdentifier}' in namespace '${namespace}'`)\n .join(', ')}`\n","import type { DeviceRequestMatchResult } from '../utils/matchDeviceRequest.js'\nimport { VerificationError } from './errors.js'\n\n/**\n * The structured result of a check that has more to report than a reason string, discriminated by\n * `type`. A check that produces one attaches it to its {@link VerificationAssessment}, so that it\n * reaches both a callback that collects the checks and the {@link VerificationError} the default\n * callback throws.\n */\nexport type VerificationAssessmentResult = {\n type: 'deviceRequestMatch'\n match: DeviceRequestMatchResult\n}\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 * The structured result of the check, for the checks that produce one.\n */\n result?: VerificationAssessmentResult\n}\n\nexport type VerificationCallback = (item: VerificationAssessment) => void\n\nexport const defaultVerificationCallback: VerificationCallback = (verification) => {\n if (verification.status !== 'FAILED') return\n throw new VerificationError(verification.reason ?? verification.check, verification)\n}\n\nexport const onCategoryCheck = (onCheck: VerificationCallback, category: VerificationAssessment['category']) => {\n return (item: Omit<VerificationAssessment, 'category'>) => {\n onCheck({ ...item, category })\n }\n}\n","import { cborDecode, DataItem } from '@owf/cose'\n\n/**\n * The bytes of an encoded structure, without the tag 24 (encoded CBOR data item) it may be wrapped in.\n */\nexport const unwrapDataItemBytes = (bytes: Uint8Array) => {\n const decoded = cborDecode(bytes, { unwrapTopLevelDataItem: false })\n return new Uint8Array(decoded instanceof DataItem ? decoded.buffer : bytes)\n}\n","import {\n type AnyCborStructure,\n type CborEncodeOptions,\n CborStructure,\n type CborStructureStaticThis,\n cborEncode,\n DataItem,\n TypedMap,\n} from '@owf/cose'\nimport { unwrapDataItemBytes } from '../utils/cbor'\n\n/**\n * A CBOR structure that keeps the bytes it was decoded from, and encodes with them until it is\n * modified.\n *\n * ISO/IEC 18013-5 8.1: \"the bytestrings shall be used as they are sent or received\". Structures that\n * are embedded as bytes in a signed, MACed or hashed structure are therefore embedded as received, as\n * re-encoding the decoded structure may give other bytes, for instance for floats, tag 0 dates with\n * fractional seconds, indefinite lengths or non-shortest encodings of another encoder.\n *\n * The bytes are kept when the structure is decoded with {@link decode} or {@link fromDataItem}, so a\n * parent structure has to decode it from its data item with `fromDataItem`, and embed it with\n * {@link asDataItem}.\n *\n * Setting or deleting an entry of a structure that is a `TypedMap` drops the bytes on its own. Call\n * {@link markModified} after changing the structure in any other way, such as a nested value.\n */\nexport class OriginalBytesCborStructure<\n EncodedStructure = unknown,\n DecodedStructure = EncodedStructure,\n> extends CborStructure<EncodedStructure, DecodedStructure> {\n #originalBytes?: Uint8Array\n\n public constructor(structure: DecodedStructure) {\n super(structure)\n\n if (structure instanceof TypedMap) {\n structure.onChange = () => this.markModified()\n }\n }\n\n /**\n * The bytes this structure was decoded from, without tag 24, if it was decoded and has not been\n * modified since.\n */\n public get originalBytes() {\n return this.#originalBytes\n }\n\n /**\n * Drops the {@link originalBytes}, so that the structure is re-encoded the next time it is encoded.\n */\n public markModified() {\n this.#originalBytes = undefined\n }\n\n /**\n * Accepts the encoded structure as well as the structure wrapped in tag 24.\n */\n public static override decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n // biome-ignore lint/complexity/noThisInStatic: `super.decode` keeps `this` bound to the subclass\n const structure = super.decode(bytes) as T\n\n if (structure instanceof OriginalBytesCborStructure) {\n structure.#originalBytes = unwrapDataItemBytes(bytes)\n }\n\n return structure\n }\n\n public static override fromDataItem<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n dataItem: unknown\n ): T {\n // biome-ignore lint/complexity/noThisInStatic: `super.fromDataItem` keeps `this` bound to the subclass\n const structure = super.fromDataItem(dataItem) as T\n\n if (structure instanceof OriginalBytesCborStructure && dataItem instanceof DataItem) {\n structure.#originalBytes = new Uint8Array(dataItem.buffer)\n }\n\n return structure\n }\n\n public override encode(options?: CborEncodeOptions): Uint8Array {\n if (!this.#originalBytes) return super.encode(options)\n\n return options?.asDataItem ? cborEncode(this.asDataItem) : this.#originalBytes\n }\n\n /**\n * This structure as a tag 24 data item, with the bytes it was received as if it was decoded.\n */\n public get asDataItem(): DataItem<EncodedStructure> {\n return DataItem.fromBuffer<EncodedStructure>(this.encode())\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\n return this.fromEncodedStructure(options.deviceSignedItems)\n }\n}\n","import { z } from 'zod'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport type { DataElementValue } from './data-element-value'\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 OriginalBytesCborStructure<\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 /**\n * The device namespaces. Call {@link markModified} after changing them in place, or use\n * {@link setDeviceNamespace} and {@link setDeviceSignedElement}.\n */\n public get deviceNamespaces() {\n return this.structure\n }\n\n public getDeviceNamespace(namespace: Namespace) {\n return this.structure.get(namespace)\n }\n\n public setDeviceNamespace(namespace: Namespace, deviceSignedItems: DeviceSignedItems) {\n this.structure.set(namespace, deviceSignedItems)\n this.markModified()\n }\n\n /**\n * Sets an element in a namespace, and adds the namespace if it is not there yet.\n */\n public setDeviceSignedElement(\n namespace: Namespace,\n elementIdentifier: DataElementIdentifier,\n elementValue: DataElementValue\n ) {\n const deviceSignedItems = this.structure.get(namespace)\n\n if (deviceSignedItems) {\n deviceSignedItems.deviceSignedItems.set(elementIdentifier, elementValue)\n this.markModified()\n } else {\n this.setDeviceNamespace(\n namespace,\n DeviceSignedItems.create({ deviceSignedItems: new Map([[elementIdentifier, elementValue]]) })\n )\n }\n }\n\n public static create(options: DeviceNamespacesOptions): DeviceNamespaces {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import { TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\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 // 18013-5 8.2.1.1: ServerRetrievalMethods = { ? \"webApi\" : WebApi, ? \"oidc\" : Oidc }, a single map.\n [DeviceEngagementKeys.ServerRetrievalMethods, 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?: ServerRetrievalMethod\n protocolInfo?: ProtocolInfo\n}\n\nexport class DeviceEngagement extends OriginalBytesCborStructure<\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 map.set(\n DeviceEngagementKeys.ServerRetrievalMethods,\n ServerRetrievalMethod.fromEncodedStructure(\n input.get(DeviceEngagementKeys.ServerRetrievalMethods) as ServerRetrievalMethodEncodedStructure\n )\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(DeviceEngagementKeys.ServerRetrievalMethods, serverRetrievalMethods.encodedStructure)\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: DeviceEngagementDecodedStructure = new TypedMap([\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import {\n type AnyCborStructure,\n type CborEncodeOptions,\n type CborStructureStaticThis,\n CoseKey,\n type CoseKeyDecodedStructure,\n type CoseKeyEncodedStructure,\n type CoseKeyOptions,\n cborEncode,\n DataItem,\n} from '@owf/cose'\nimport { unwrapDataItemBytes } from '../../utils/cbor'\n\nexport type EReaderKeyDecodedStructure = CoseKeyDecodedStructure\nexport type EReaderKeyEncodedStructure = CoseKeyEncodedStructure\nexport type EReaderKeyOptions = CoseKeyOptions\n\n/**\n * A `CoseKey` for the ephemeral key of the mdoc reader, which keeps the bytes it was decoded from the\n * way `OriginalBytesCborStructure` does, as `EReaderKeyBytes` are part of the session transcript\n * (18013-5 8.1). It extends `CoseKey`, so it cannot extend `OriginalBytesCborStructure`.\n */\nexport class EReaderKey extends CoseKey {\n #originalBytes?: Uint8Array\n\n public static override create(options: EReaderKeyOptions): EReaderKey {\n // biome-ignore lint/complexity/noThisInStatic: `super.create` keeps `this` bound to the subclass\n return super.create(options) as EReaderKey\n }\n\n public static override fromJwk(jwk: Record<string, unknown>): EReaderKey {\n // biome-ignore lint/complexity/noThisInStatic: `super.fromJwk` keeps `this` bound to the subclass\n return super.fromJwk(jwk) as EReaderKey\n }\n\n /**\n * The bytes this reader key was decoded from, if it was decoded. A decoded reader key encodes as it\n * was received, as `EReaderKeyBytes` are part of the session transcript (18013-5 8.1).\n */\n public get originalBytes() {\n return this.#originalBytes\n }\n\n public static override decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n // biome-ignore lint/complexity/noThisInStatic: `super.decode` keeps `this` bound to the subclass\n const eReaderKey = super.decode(bytes) as unknown as T\n if (eReaderKey instanceof EReaderKey) eReaderKey.#originalBytes = unwrapDataItemBytes(bytes)\n return eReaderKey\n }\n\n public static override fromDataItem<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n dataItem: unknown\n ): T {\n // biome-ignore lint/complexity/noThisInStatic: `super.fromDataItem` keeps `this` bound to the subclass\n const eReaderKey = super.fromDataItem(dataItem) as unknown as T\n if (eReaderKey instanceof EReaderKey && dataItem instanceof DataItem) {\n eReaderKey.#originalBytes = new Uint8Array(dataItem.buffer)\n }\n return eReaderKey\n }\n\n public override encode(options?: CborEncodeOptions): Uint8Array {\n if (!this.#originalBytes) return super.encode(options)\n return options?.asDataItem ? cborEncode(this.asDataItem) : this.#originalBytes\n }\n\n /**\n * This reader key as a tag 24 data item, with the bytes it was received as if it was decoded.\n */\n public get asDataItem(): DataItem<EReaderKeyEncodedStructure> {\n return DataItem.fromBuffer<EReaderKeyEncodedStructure>(this.encode())\n }\n}\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 public get requiresReaderKey() {\n return false\n }\n\n public get requiresDeviceEngagement() {\n return false\n }\n}\n","import { zUint8Array } from '@owf/cose'\nimport type z from 'zod'\nimport { Handover } from './handover'\n\nconst engagementToAppHandoverSchema = zUint8Array\nexport type EngagementToAppHandoverStructure = z.infer<typeof engagementToAppHandoverSchema>\n\n/**\n * The handover of ISO/IEC TS 18013-7 Annex A, device retrieval to a website.\n *\n * A.8 defines it as a bare byte string:\n *\n * Handover = EngagementToApp / any\n * EngagementToApp = ReaderEngagementBytesHash\n * ReaderEngagementBytesHash = bstr\n * ReaderEngagementBytes = #6.24(bstr .cbor ReaderEngagement)\n *\n * where the hash is SHA-256 of ReaderEngagementBytes. Computing it is the\n * caller's business, since only the reader and the mdoc hold the\n * ReaderEngagement; this class is the CBOR shape.\n *\n * It is the only handover that is not a tuple or null, so it can never be\n * confused with one of the others when a SessionTranscript is decoded.\n */\nexport class EngagementToAppHandover extends Handover<EngagementToAppHandoverStructure> {\n public static override get encodingSchema() {\n return engagementToAppHandoverSchema\n }\n\n public get readerEngagementBytesHash() {\n return this.structure\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(readerEngagementBytesHash: Uint8Array) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(readerEngagementBytesHash)\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 { EngagementToAppHandover } from './engagement-to-app-handover'\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 // Last because it is the least specific: a bare bstr. None of the\n // others can match one, so the position is a readability choice\n // rather than a correctness one.\n EngagementToAppHandover,\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.fromDataItem(deviceEngagementDataItem)\n : null\n const eReaderKey = eReaderKeyDataItem ? EReaderKey.fromDataItem(eReaderKeyDataItem) : 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 // DeviceEngagementBytes and EReaderKeyBytes are embedded as received.\n deviceEngagement ? deviceEngagement.asDataItem : null,\n eReaderKey ? eReaderKey.asDataItem : 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 /**\n * A session transcript passed as bytes is either `SessionTranscript` or `SessionTranscriptBytes`\n * (tagged with tag 24).\n */\n public static from(sessionTranscript: SessionTranscript | Uint8Array): SessionTranscript {\n return sessionTranscript instanceof SessionTranscript\n ? sessionTranscript\n : SessionTranscript.decode(sessionTranscript)\n }\n\n public static create(options: SessionTranscriptOptions): SessionTranscript {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 returns the identical bytes.\n */\n public static forQrHandover(options: { deviceEngagement: DeviceEngagement; eReaderKey: EReaderKey }) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure({\n deviceEngagement: options.deviceEngagement,\n eReaderKey: options.eReaderKey,\n handover: QrHandover.create(),\n })\n }\n\n /**\n * Create a SessionTranscript for ISO/IEC TS 18013-7 Annex A, device\n * retrieval to a website.\n *\n * `readerEngagementBytesHash` is SHA-256 of\n * `#6.24(bstr .cbor ReaderEngagement)`, per A.8. As with QR handover the\n * exact CBOR bytes matter for session key derivation, so pass a\n * DeviceEngagement and an EReaderKey obtained through `decode()`.\n */\n public static forEngagementToApp(options: {\n deviceEngagement: DeviceEngagement\n eReaderKey: EReaderKey\n readerEngagementBytesHash: Uint8Array\n }) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure({\n deviceEngagement: options.deviceEngagement,\n eReaderKey: options.eReaderKey,\n handover: EngagementToAppHandover.create(options.readerEngagementBytesHash),\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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.fromDataItem(deviceNamespacesDataItem),\n }),\n encode: ({ sessionTranscript, docType, deviceNamespaces }) =>\n [\n 'DeviceAuthentication',\n sessionTranscript.encodedStructure,\n docType,\n // `DeviceNameSpacesBytes` are authenticated as the mdoc sent them (18013-5 8.1).\n deviceNamespaces.asDataItem,\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure({\n sessionTranscript: SessionTranscript.from(options.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 // biome-ignore lint/complexity/noThisInStatic: `super.create` keeps `this` bound to the subclass\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 // 18013-5 9.1.3.5: the salt is SHA-256(SessionTranscriptBytes), so the transcript tagged with tag 24.\n salt: await ctx.crypto.digest({\n digestAlgorithm: 'SHA-256',\n bytes: SessionTranscript.from(options.sessionTranscript).encode({ asDataItem: true }),\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 {\n collectDeviceSignedElements,\n describeUnauthorizedDeviceSignedElements,\n findUnauthorizedDeviceSignedElements,\n} from '../../utils/keyAuthorizations'\nimport {\n defaultVerificationCallback,\n onCategoryCheck,\n type VerificationAssessment,\n type VerificationCallback,\n} 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)\n\n// ISO/IEC 18013-5 9.1.3.4: DeviceAuth = { \"deviceSignature\" : DeviceSignature // \"deviceMac\" : DeviceMac }\n// The refinement is applied to the decoded schema, as both decoding and `fromDecodedStructure` validate against it.\nconst deviceAuthDecodedSchema = deviceAuthSchema.out.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, deviceAuthDecodedSchema, {\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 this.verifyKeyAuthorizations(options.document, onCheck)\n\n const deviceMac = this.structure.get('deviceMac')\n const deviceSignature = this.structure.get('deviceSignature')\n\n // The schema already enforces this, but a signature must never be accepted while a MAC is also present\n const hasExactlyOneAuthentication = (deviceSignature === undefined) !== (deviceMac === undefined)\n onCheck({\n status: hasExactlyOneAuthentication ? 'PASSED' : 'FAILED',\n check: 'Device Auth must contain either a deviceSignature or deviceMac element, but not both',\n })\n if (!hasExactlyOneAuthentication) {\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 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\n /**\n * The mdoc reader half of the ISO/IEC 18013-5 9.1.3.4 key authorization rule, which\n * {@link findUnauthorizedDeviceSignedElements} states in full. `DeviceResponse` enforces the\n * mdoc half of the same rule when it creates a response.\n */\n private verifyKeyAuthorizations(\n document: Document,\n onCheck: (item: Omit<VerificationAssessment, 'category'>) => void\n ) {\n const { deviceNamespaces } = document.deviceSigned\n\n // The check only applies when the mdoc actually authenticated device-signed elements.\n if (collectDeviceSignedElements(deviceNamespaces).length === 0) return\n\n const unauthorized = findUnauthorizedDeviceSignedElements({\n deviceNamespaces,\n keyAuthorizations: document.issuerSigned.issuerAuth.mobileSecurityObject.deviceKeyInfo.keyAuthorizations,\n })\n\n onCheck({\n status: unauthorized.length === 0 ? 'PASSED' : 'FAILED',\n check: 'Device signed elements must be authorized by the key authorizations in the mobile security object',\n reason: unauthorized.length ? describeUnauthorizedDeviceSignedElements(unauthorized) : undefined,\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import type { VerificationCallback } from '../mdoc/check-callback'\nimport type { DataElementIdentifier } from '../mdoc/models/data-element-identifier'\nimport type { DataElementValue } from '../mdoc/models/data-element-value'\nimport type { DeviceRequest } from '../mdoc/models/device-request'\nimport type { ItemsRequest } from '../mdoc/models/items-request'\nimport type { Namespace } from '../mdoc/models/namespace'\n\n/**\n * ISO/IEC 18013-5 7.2.5: `NN` is always two digits, from `00` to `99`.\n */\nconst ageOverIdentifierPattern = /^age_over_(\\d{2})$/\nconst maximumAgeOverRequests = 2\n\nexport type AgeOverCandidate = {\n elementIdentifier: DataElementIdentifier\n elementValue: DataElementValue\n}\n\n/**\n * The `NN` of an `age_over_NN` element identifier, or `undefined` when the identifier is not an\n * age attestation. `NN` must be exactly two digits, so `age_over_8`, `age_over_018` and\n * `age_over_18a` are not age attestations.\n */\nexport const parseAgeOverIdentifier = (elementIdentifier: DataElementIdentifier): number | undefined => {\n const match = ageOverIdentifierPattern.exec(elementIdentifier)\n return match ? Number(match[1]) : undefined\n}\n\n/**\n * Find the `age_over_MM` attestation that answers a request for `age_over_NN`.\n *\n * ISO/IEC 18013-5 7.2.5 lets the mdoc answer with a different age attestation than the one\n * requested: the nearest one that is `true` for `MM >= NN`, and otherwise the nearest one that is\n * `false` for `MM <= NN`.\n */\nexport const findAgeOverCandidate = <Candidate extends AgeOverCandidate>(\n requestedElementIdentifier: DataElementIdentifier,\n candidates: Array<Candidate>\n): Candidate | undefined => {\n const requestedNn = parseAgeOverIdentifier(requestedElementIdentifier)\n if (requestedNn === undefined) return undefined\n\n const ageOverCandidates = candidates.flatMap((candidate) => {\n const nn = parseAgeOverIdentifier(candidate.elementIdentifier)\n return nn === undefined ? [] : [{ nn, candidate }]\n })\n\n const nearestTrue = ageOverCandidates\n .filter(({ nn, candidate }) => candidate.elementValue === true && nn >= requestedNn)\n .sort((a, b) => a.nn - b.nn)[0]\n if (nearestTrue) return nearestTrue.candidate\n\n const nearestFalse = ageOverCandidates\n .filter(({ nn, candidate }) => candidate.elementValue === false && nn <= requestedNn)\n .sort((a, b) => b.nn - a.nn)[0]\n\n return nearestFalse?.candidate\n}\n\n/**\n * The namespaces with more than two distinct `age_over_NN` element identifiers, with those\n * identifiers.\n *\n * ISO/IEC 18013-5 7.2.5: \"an mDL reader shall not request more than two age_over_NN data elements\".\n * Counted per namespace, as an age attestation only answers requests in its own namespace.\n */\nexport const findAgeOverLimitViolations = (\n namespaces: Iterable<readonly [Namespace, Iterable<DataElementIdentifier>]>\n): Array<AgeOverLimitViolation> =>\n Array.from(namespaces, ([namespace, elementIdentifiers]) => ({\n namespace,\n ageOverIdentifiers: Array.from(new Set(elementIdentifiers)).filter(\n (elementIdentifier) => parseAgeOverIdentifier(elementIdentifier) !== undefined\n ),\n })).filter(({ ageOverIdentifiers }) => ageOverIdentifiers.length > maximumAgeOverRequests)\n\nexport type AgeOverLimitViolation = {\n namespace: Namespace\n ageOverIdentifiers: Array<DataElementIdentifier>\n}\n\n/**\n * {@link findAgeOverLimitViolations} for the namespaces of an `ItemsRequest`.\n */\nexport const findAgeOverRequestLimitViolations = (namespaces: ItemsRequest['namespaces']) =>\n findAgeOverLimitViolations(Array.from(namespaces, ([namespace, elements]) => [namespace, elements.keys()] as const))\n\n/**\n * E.g. `'age_over_18', 'age_over_21', 'age_over_65' in namespace 'org.iso.18013.5.1'`.\n */\nexport const describeAgeOverLimitViolations = (violations: Array<AgeOverLimitViolation>) =>\n violations\n .map(\n ({ namespace, ageOverIdentifiers }) =>\n `${ageOverIdentifiers.map((elementIdentifier) => `'${elementIdentifier}'`).join(', ')} in namespace '${namespace}'`\n )\n .join(' and ')\n\n/**\n * Report through `onCheck` whether every doc request of `deviceRequest` requests at most two\n * `age_over_NN` elements per namespace (18013-5 7.2.5).\n */\nexport const verifyAgeOverRequestLimit = (deviceRequest: DeviceRequest, onCheck: VerificationCallback) => {\n const reasons = deviceRequest.docRequests.flatMap((docRequest, docRequestIndex) => {\n const violations = findAgeOverRequestLimitViolations(docRequest.itemsRequest.namespaces)\n return violations.length === 0\n ? []\n : [`Doc request ${docRequestIndex} requests ${describeAgeOverLimitViolations(violations)}`]\n })\n\n onCheck({\n status: reasons.length === 0 ? 'PASSED' : 'FAILED',\n category: 'DOCUMENT_FORMAT',\n check: `Device request must not request more than ${maximumAgeOverRequests} age_over_NN elements per namespace`,\n reason: reasons.length === 0 ? undefined : reasons.join('; '),\n })\n}\n","import { typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { describeAgeOverLimitViolations, findAgeOverRequestLimitViolations } from '../../utils/ageOver'\nimport { AgeOverLimitExceededError } from '../errors'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\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 OriginalBytesCborStructure<\n ItemsRequestEncodedStructure,\n ItemsRequestDecodedStructure\n> {\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 /**\n * Throws an `AgeOverLimitExceededError` when more than two `age_over_NN` elements are requested in\n * a namespace (18013-5 7.2.5). A decoded items request is not checked, so that the mdoc can report\n * such a request instead.\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 violations = findAgeOverRequestLimitViolations(namespaces)\n if (violations.length > 0) {\n throw new AgeOverLimitExceededError(\n `Items request for docType '${options.docType}' requests ${describeAgeOverLimitViolations(violations)}, but at most two age_over_NN elements may be requested per namespace`\n )\n }\n\n const structure = new Map<unknown, unknown>([\n ['docType', options.docType],\n ['nameSpaces', namespaces],\n ])\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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.fromDataItem(itemsRequestDataItem),\n }),\n encode: ({ sessionTranscript, itemsRequest }) =>\n [\n 'ReaderAuthentication',\n sessionTranscript.encodedStructure,\n // `ItemsRequestBytes` are signed as the mdoc reader sent them (18013-5 8.1).\n itemsRequest.asDataItem,\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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). The chain in this Sign1's x5chain header is validated against\n * these anchors per RFC 5280. Without trust anchors the chain check FAILS,\n * unless `disableCertificateChainValidation` is set.\n */\n trustedCertificates?: Array<Uint8Array>\n /**\n * Only verify the detached signature, without establishing trust in the\n * reader's certificate chain. The reader is then not authenticated.\n */\n disableCertificateChainValidation?: boolean\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 let isValid: boolean\n let reason: string | undefined\n try {\n // `certificate` throws when the reader auth has no x5chain, which is required (18013-5 9.1.4).\n 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 reason = isValid ? undefined : 'Signature is invalid on the reader auth'\n } catch (error) {\n isValid = false\n reason = `Unable to verify the reader auth signature: ${error instanceof Error ? error.message : 'Unknown error'}`\n }\n\n onCheck({\n status: isValid ? 'PASSED' : 'FAILED',\n check: 'Reader auth signature must be valid',\n reason,\n })\n\n if (!options.disableCertificateChainValidation) {\n try {\n if (!options.trustedCertificates || 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 // biome-ignore lint/complexity/noThisInStatic: `super.create` keeps `this` bound to the subclass\n return super.create(options) as ReaderAuth\n }\n}\n","import { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { ItemsRequest } 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 map.set('itemsRequest', ItemsRequest.fromDataItem(input.get('itemsRequest')))\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 // `ItemsRequestBytes` are embedded as received, as reader authentication signs them.\n map.set('itemsRequest', output.get('itemsRequest').asDataItem)\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","/**\n * The value of an own property of `record`, so that a key such as `constructor` or `toString` does\n * not resolve to a property of `Object.prototype`. Namespaces and element identifiers come from the\n * device request, so they are used as keys as they are.\n */\nexport const getOwnProperty = <Value>(record: Record<string, Value> | undefined, key: string): Value | undefined =>\n // biome-ignore lint/suspicious/noPrototypeBuiltins: `Object.hasOwn` is not in the ES2020 lib this package targets\n record && Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined\n","import type { VerificationCallback } from '../mdoc/check-callback'\n\n/**\n * ISO/IEC 18013-5 8.1: a version is `major.minor`, and an unknown minor version of a known major\n * version must not cause an error. Every structure this library supports has major version 1.\n */\nexport const supportedVersionRegex = /^1\\.\\d+$/\n\nexport const isSupportedVersion = (version: string) => supportedVersionRegex.test(version)\n\n/**\n * Report through `onCheck` whether the version of a structure has a major version this library\n * supports.\n */\nexport const verifyVersion = (\n options: { structure: string; version: string | undefined },\n onCheck: VerificationCallback\n) => {\n const { structure, version } = options\n\n onCheck({\n status: version !== undefined && isSupportedVersion(version) ? 'PASSED' : 'FAILED',\n category: 'DOCUMENT_FORMAT',\n check: `${structure} must have a supported version`,\n reason:\n version !== undefined && isSupportedVersion(version)\n ? undefined\n : `${structure} has version '${version}', but only major version 1 is supported`,\n })\n}\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\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 { supportedVersionRegex } from '../../utils/version'\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 ['version', z.string().regex(supportedVersionRegex)],\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 const status = input.get('status')\n if (status === null) {\n // NOTE: null is NOT allowed, but Apple Wallet's developer mDLs send it. Status is optional, so we\n // read null as absent and drop the entry TypedMap.fromMap copied.\n map.delete('status')\n } else if (input.has('status')) {\n map.set('status', Status.fromEncodedStructure(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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import {\n type CoseHeadersFor,\n extendCoseHeaderClaims,\n ProtectedHeaders,\n protectedHeadersSchema,\n RegisteredCwtHeaderClaimKey,\n} from '@owf/cose'\nimport z from 'zod'\n\n/** CWT media types used by the ISO/IEC 18013-5 revocation mechanisms. */\nexport enum MediaTypes {\n IdentifierListCwt = 'application/identifierlist+cwt',\n}\n\n// § 12.3.6.4: \"The value of the type claim shall be 'application/identifierlist+cwt'\".\n// `typ` is a COSE header parameter (RFC 9596, label 16), not a CWT claim — the same place\n// `@owf/token-status-list` writes it on a status list CWT. Required in the protected bucket\n// specifically: RFC 9596 forbids `typ` in the unprotected headers, so an unprotected copy is\n// not integrity protected, and `Cwt.typ` ignores it.\nconst identifierListCwtProtectedHeaderClaims = extendCoseHeaderClaims([\n [\n RegisteredCwtHeaderClaimKey.Typ,\n z.literal(MediaTypes.IdentifierListCwt, {\n error: `Typ (protected header 16) shall be '${MediaTypes.IdentifierListCwt}' (ISO 18013-5 § 12.3.6.4)`,\n }),\n ],\n] as const)\n\n/**\n * The protected COSE headers of an identifier list CWT (ISO/IEC 18013-5 second edition\n * § 12.3.6.4): the registered COSE header claims, with `typ` (16) required and narrowed to the\n * identifier list media type.\n *\n * `alg` and `x5chain` are already typed by the registered claims, so they are not redeclared.\n */\nexport class IdentifierListCwtProtectedHeaders extends ProtectedHeaders<\n CoseHeadersFor<typeof identifierListCwtProtectedHeaderClaims>\n> {\n public static override get encodingSchema() {\n return protectedHeadersSchema(identifierListCwtProtectedHeaderClaims)\n }\n\n /**\n * Leaf certificate and chain from the `x5chain` header (RFC 9360 label 33), normalized to an\n * array. § 12.3.6.3 requires it: \"The CWT shall contain the x5chain in the protected header\".\n */\n public get x5chain(): Array<Uint8Array> | undefined {\n const x5chain = this.headers.get(RegisteredCwtHeaderClaimKey.X5Chain)\n return x5chain instanceof Uint8Array ? [x5chain] : x5chain\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import {\n type CreateCwtPayloadOptions,\n CwtClaimVerificationError,\n CwtPayload,\n cwtPayloadClaimsFromOptions,\n extendCwtPayloadClaims,\n RegisteredCwtClaimKey,\n TypedMap,\n type VerifyCwtClaimsOptions,\n} from '@owf/cose'\nimport { StatusListCwtClaimKey } from '@owf/token-status-list'\nimport z from 'zod'\nimport { InvalidRevocationListError } from '../errors'\nimport { IdentifierList, type IdentifierListEncodedStructure } from './identifier-list'\n\n/**\n * CWT payload claim carrying the identifier list (ISO/IEC 18013-5 second edition § 12.3.6.4).\n * Mirrors `StatusListCwtClaimKey` from `@owf/token-status-list`.\n */\nexport enum IdentifierListCwtClaimKey {\n IdentifierList = 65530,\n}\n\n/**\n * The registered CWT claims, with the ones an identifier list CWT requires narrowed to\n * non-optional, plus the identifier list claim itself.\n */\nconst identifierListCwtPayloadSchema = extendCwtPayloadClaims(\n [\n // § 12.3.6.3 defers to the Token Status List specification, where `sub` and `iat` are\n // REQUIRED claims of a Status List Token. `sub` shall equal the `uri` of the\n // `IdentifierListInfo` that pointed here; that equality is checked by `verifyClaims`.\n [RegisteredCwtClaimKey.Subject, z.string()],\n [RegisteredCwtClaimKey.IssuedAt, z.number()],\n // § 12.3.6.3: \"The exp claim shall be present.\"\n [RegisteredCwtClaimKey.ExpirationTime, z.number()],\n [IdentifierListCwtClaimKey.IdentifierList, z.instanceof(IdentifierList)],\n // § 12.3.6.4: \"The StatusList claim shall not be present in the CWT claims set.\" Declared as\n // `never` rather than checked afterwards, so the two revocation mechanisms cannot be mixed in\n // one token and the claims set is rejected where every other claim is validated.\n [\n StatusListCwtClaimKey.StatusList,\n z\n .never({\n error: `The StatusList claim (${StatusListCwtClaimKey.StatusList}) shall not be present in an identifier list CWT (ISO 18013-5 § 12.3.6.4)`,\n })\n .exactOptional(),\n ],\n ] as const,\n { keyLabels: { ...IdentifierListCwtClaimKey, ...StatusListCwtClaimKey } }\n)\n\nexport type IdentifierListCwtPayloadEncodedStructure = z.input<typeof identifierListCwtPayloadSchema>\nexport type IdentifierListCwtPayloadDecodedStructure = z.infer<typeof identifierListCwtPayloadSchema>\n\nexport type CreateIdentifierListCwtPayloadOptions = Omit<CreateCwtPayloadOptions, 'subject' | 'expirationTime'> & {\n identifierList: IdentifierList\n\n /**\n * URI the list is published at. Becomes the `sub` claim, and shall equal the `uri` of the MSO's\n * `IdentifierListInfo`.\n */\n uri: string\n\n /** § 12.3.6.3: \"The exp claim shall be present.\" */\n expirationTime: Date\n}\n\n/**\n * The options {@link IdentifierListCwtPayload.verifyClaims} takes: the generic CWT ones, with `sub`\n * replaced by the `uri` it has to be equal to. Matches `VerifyStatusListCwtClaimsOptions`, so both\n * revocation mechanisms are verified through the same shape.\n */\nexport type VerifyIdentifierListCwtClaimsOptions = Omit<VerifyCwtClaimsOptions, 'expectedSubject' | 'keyLabels'> & {\n /** The `uri` of the `IdentifierListInfo` the token was fetched for, which `sub` must equal. */\n uri: string\n}\n\n/**\n * The claims set of an identifier list CWT (ISO/IEC 18013-5 second edition § 12.3.6.4).\n *\n * The registered claims — `sub`, `iat`, `exp` — come from {@link CwtPayload}, and narrow to\n * non-optional here because the schema above redeclares them as required.\n */\nexport class IdentifierListCwtPayload extends CwtPayload<IdentifierListCwtPayloadDecodedStructure> {\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 override create(options: CreateIdentifierListCwtPayloadOptions) {\n // `iat` is required for a status list token, so it defaults to now rather than being omitted.\n // NOTE: applied after the spread, so that an explicit `issuedAt: undefined` — what passing\n // through an optional value gives — defaults the same way omitting the key does.\n const claims = cwtPayloadClaimsFromOptions({\n ...options,\n subject: options.uri,\n issuedAt: options.issuedAt ?? new Date(),\n })\n\n claims.set(IdentifierListCwtClaimKey.IdentifierList, options.identifierList)\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(TypedMap.fromMap(claims))\n }\n\n /** `identifier_list` (65530) */\n public get identifierList(): IdentifierList {\n return this.getClaim(IdentifierListCwtClaimKey.IdentifierList)\n }\n\n /**\n * Verifies the claims of an identifier list token, on top of the generic CWT ones. § 12.3.6.1\n * makes the Token Status List verification requirements binding on both revocation mechanisms,\n * so `sub` and `iat` are REQUIRED and `sub` has to match the URI the token was referenced by —\n * without that check a list published for one URI can be replayed for another under the same\n * trust anchor. § 12.3.6.3 additionally requires `exp`.\n *\n * The counterpart of `StatusListCwtPayload.verifyClaims`, with the same defaults, including a\n * 30 second clock skew tolerance.\n *\n * @throws InvalidRevocationListError if a required claim is missing, `sub` is not the referenced\n * URI, or the token is outside its validity window.\n */\n public override verifyClaims({ uri, requiredClaims = [], ...options }: VerifyIdentifierListCwtClaimsOptions): void {\n try {\n super.verifyClaims({\n ...options,\n expectedSubject: uri,\n requiredClaims: [\n RegisteredCwtClaimKey.Subject,\n RegisteredCwtClaimKey.IssuedAt,\n RegisteredCwtClaimKey.ExpirationTime,\n ...requiredClaims,\n ],\n keyLabels: IdentifierListCwtClaimKey,\n })\n } catch (error) {\n if (error instanceof CwtClaimVerificationError) {\n throw new InvalidRevocationListError(`Identifier list token claim verification failed. ${error.message}`)\n }\n\n throw error\n }\n }\n}\n","import {\n type AnyCwt,\n Cwt,\n type CwtOptions,\n type CwtStaticThis,\n type CwtStructures,\n type CwtVerifyContext,\n type CwtVerifyOptions,\n ProtectedHeaders,\n RegisteredCwtHeaderClaimKey,\n TypedMap,\n type UnprotectedHeaderOptions,\n type UnprotectedHeaders,\n} from '@owf/cose'\nimport { hex, isMediaType } from '@owf/identity-common'\nimport type { MdocContext } from '../../context'\nimport { IdentifierFoundInRevokedListError, InvalidRevocationListError } from '../errors'\nimport { IdentifierListCwtProtectedHeaders, MediaTypes } from './identifier-list-cwt-headers'\nimport {\n type CreateIdentifierListCwtPayloadOptions,\n IdentifierListCwtClaimKey,\n IdentifierListCwtPayload,\n} from './identifier-list-cwt-payload'\n\nexport type IdentifierListCwtOptions = Omit<\n CwtOptions<IdentifierListCwtPayload, IdentifierListCwtProtectedHeaders>,\n 'payload' | 'protectedHeaders'\n> & {\n payload: IdentifierListCwtPayload | CreateIdentifierListCwtPayloadOptions\n\n /**\n * The protected headers. `typ` (16) is set to the identifier list media type when absent, so only\n * the one value it is allowed to have has to be supplied.\n */\n protectedHeaders?: IdentifierListCwtProtectedHeaders | ProtectedHeaders | Map<number, unknown>\n\n unprotectedHeaders?: UnprotectedHeaders | UnprotectedHeaderOptions['unprotectedHeaders']\n}\n\n/**\n * Builds the protected headers of an identifier list CWT, defaulting `typ` (16) to the identifier\n * list media type. Validated against {@link IdentifierListCwtProtectedHeaders}, so a `typ` that is\n * present but says the token is something else is rejected here rather than silently overwritten.\n */\nfunction identifierListProtectedHeaders(\n protectedHeaders: IdentifierListCwtOptions['protectedHeaders']\n): IdentifierListCwtProtectedHeaders {\n if (protectedHeaders instanceof IdentifierListCwtProtectedHeaders) return protectedHeaders\n\n const headers = new Map<number, unknown>(\n protectedHeaders instanceof ProtectedHeaders ? protectedHeaders.decodedStructure : protectedHeaders\n )\n if (headers.get(RegisteredCwtHeaderClaimKey.Typ) === undefined) {\n headers.set(RegisteredCwtHeaderClaimKey.Typ, MediaTypes.IdentifierListCwt)\n }\n\n return IdentifierListCwtProtectedHeaders.fromDecodedStructure(TypedMap.fromMap(headers))\n}\n\n/**\n * A revocation list token in CWT format that enumerates revoked MSO identifiers, rather than\n * indexing statuses by position (ISO/IEC 18013-5 second edition § 12.3.6.4). Presence of an\n * identifier means the MSO carrying it is revoked; absence means it is valid.\n *\n * The counterpart of `StatusListCwt` from `@owf/token-status-list`, and built the same way: the\n * claims set and protected headers validate themselves, and this class only names them and adds\n * what is specific to an identifier list.\n */\nexport class IdentifierListCwt extends Cwt<IdentifierListCwtPayload, IdentifierListCwtProtectedHeaders> {\n public constructor(options: IdentifierListCwtOptions) {\n super({\n ...options,\n protectedHeaders: identifierListProtectedHeaders(options.protectedHeaders),\n payload:\n options.payload instanceof IdentifierListCwtPayload\n ? options.payload\n : IdentifierListCwtPayload.create(options.payload),\n })\n }\n\n /**\n * Decodes an identifier list CWT from a tagged COSE_Sign1 (tag 18) or COSE_Mac0 (tag 17) token.\n *\n * @throws CwtPayloadDecodeError if the payload is not a valid identifier list claims set.\n * @throws ZodValidationError if the protected headers do not carry the identifier list `typ`.\n */\n public static override fromToken<T extends AnyCwt>(this: CwtStaticThis<T>, token: Uint8Array): T {\n // NOTE: `super.fromToken`, not `Cwt.fromToken`: the base implementation constructs `this`, so a\n // subclass of IdentifierListCwt is what comes back. The cast is because TypeScript resolves\n // `super.fromToken` against the base class, and cannot see that `T` is made of these structures.\n // biome-ignore lint/complexity/noThisInStatic: `super.fromToken` keeps `this` bound to the subclass\n return super.fromToken(token, {\n payload: IdentifierListCwtPayload,\n protectedHeaders: IdentifierListCwtProtectedHeaders,\n } as unknown as CwtStructures<T>) as T\n }\n\n /**\n * Fetches the identifier list published at `uri`.\n *\n * The counterpart of `fetchStatusList`, which the Token Status List specification's own media\n * type has; an identifier list is an ISO addition that `@owf/token-status-list` does not know\n * about, so the content type negotiation for it lives here.\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, { headers: { Accept: MediaTypes.IdentifierListCwt } })\n\n if (!response.ok) {\n throw new InvalidRevocationListError(`Identifier list fetch at ${uri} failed with status '${response.status}'`)\n }\n\n // Token Status List § 8.2, applied to the identifier list media type by § 12.3.6.4. A response\n // without a Content-Type is let through — the token itself carries the media type in `typ`, and\n // is rejected there if it is not an identifier list.\n const contentType = response.headers.get('Content-Type')\n if (contentType !== null && !isMediaType(contentType, MediaTypes.IdentifierListCwt)) {\n throw new InvalidRevocationListError(\n `Identifier list at ${uri} was served as '${contentType}', expected '${MediaTypes.IdentifierListCwt}'`\n )\n }\n\n return IdentifierListCwt.fromToken(new Uint8Array(await response.arrayBuffer()))\n }\n\n /** Leaf certificate and chain from the CWT's protected `x5chain` header, normalized to an array. */\n public get x5chain(): Array<Uint8Array> | undefined {\n return this.protectedHeaders.x5chain\n }\n\n /** True when `id` appears in the published list, and the MSO carrying it is therefore revoked. */\n public includes(id: Uint8Array): boolean {\n return this.payload.identifierList.includes(id)\n }\n\n /**\n * Verify the token completely: its signature or authentication tag, its claims, and — when `id`\n * is given — that the MSO carrying that identifier has not been revoked. The counterpart of\n * `StatusListCwt.verify`, which takes the `idx` into the status list where this takes the `id`\n * from the MSO's `IdentifierListInfo`.\n *\n * @throws CoseInvalidSignatureError if the signature or authentication tag does not verify.\n * @throws InvalidRevocationListError if the claims do not.\n * @throws IdentifierFoundInRevokedListError if `id` is on the list.\n */\n public override async verify(\n { id, ...options }: CwtVerifyOptions<IdentifierListCwtPayload> & { id?: Uint8Array },\n ctx: CwtVerifyContext\n ): Promise<void> {\n await super.verify(options, ctx)\n\n if (id !== undefined) this.verifyStatus(id)\n }\n\n /**\n * Verify that `id` is not on this list, without verifying the remaining claims or the signature.\n *\n * @throws IdentifierFoundInRevokedListError if it is, which per § 12.3.6.4 means the MSO carrying\n * it is revoked.\n */\n public verifyStatus(id: Uint8Array): void {\n if (this.includes(id)) {\n throw new IdentifierFoundInRevokedListError(\n `Identifier ${hex.encode(id)} found in the revoked identifier list at '${this.payload.subject}'`\n )\n }\n }\n}\n\nexport { IdentifierListCwtClaimKey }\n","import {\n CoseInvalidSignatureError,\n RegisteredCwtClaimKey,\n RegisteredCwtHeaderClaimKey,\n type SignatureAlgorithm,\n} from '@owf/cose'\nimport { fetchStatusList, SLException, StatusListCwt, type StatusListInfo } from '@owf/token-status-list'\nimport type { MdocContext } from '../../context'\nimport {\n InvalidIdentifierListSignatureError,\n InvalidRevocationListError,\n InvalidSignatureError,\n JwtNotSupportForStatusListError,\n type MdlError,\n NoPublicKeySetOnStatusListError,\n TrustedRevocationCertificatesMustContainAtleastOneCertificateError,\n UnableToExtractX5ChainFromCwtError,\n UnableToExtractX5ChainFromIdentifierListError,\n} from '../errors'\nimport { IdentifierListCwt } from './identifier-list-cwt'\nimport type { IdentifierListInfo } from './identifier-list-info'\n\n/**\n * Runs the claim and status checks `@owf/cose` and `@owf/token-status-list` own, translating the\n * errors they raise into the mdoc error hierarchy so that a caller of `IssuerAuth.verify` only ever\n * has to know `MdlError`.\n */\nasync function asMdlRevocationListError(\n verification: () => Promise<unknown> | unknown,\n /** The error to report a failed signature as. */\n invalidSignatureError: new (message: string) => MdlError\n): Promise<void> {\n try {\n await verification()\n } catch (error) {\n if (error instanceof CoseInvalidSignatureError) throw new invalidSignatureError(error.message)\n if (error instanceof SLException) throw new InvalidRevocationListError(error.message)\n throw error\n }\n}\n\n/**\n * The trust anchors a revocation list signer is validated against. Also checked before the list is\n * fetched, so that a verification that cannot succeed does not request the URI in the MSO.\n */\nfunction assertTrustedCertificates({\n trustedCertificates,\n}: {\n trustedCertificates?: Array<Uint8Array>\n}): Array<Uint8Array> {\n if (!trustedCertificates || trustedCertificates.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 return trustedCertificates\n}\n\n/**\n * Establishes the signer of a revocation list: the certificate chain it carries, validated against\n * the mdoc trust anchors unless certificate chain validation is disabled, and the public key of its\n * leaf.\n *\n * § 12.3.6.3 requires the chain to travel in the protected header of the CWT: \"The CWT shall\n * contain the x5chain in the protected header that contains the certificate or chain of\n * certificates used to verify the signature\".\n */\nasync function verifyRevocationListSigner(\n {\n x5chain,\n algorithm,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n }: {\n x5chain: Array<Uint8Array>\n algorithm?: SignatureAlgorithm\n trustedCertificates?: Array<Uint8Array>\n disableCertificateChainValidation?: boolean\n now: Date\n },\n ctx: Pick<MdocContext, 'x509'>\n) {\n let chain: Array<Uint8Array> | undefined\n if (!disableCertificateChainValidation) {\n ;({ chain } = await ctx.x509.verifyCertificateChain({\n trustedCertificates: assertTrustedCertificates({ trustedCertificates }),\n x5chain,\n now,\n }))\n }\n\n const key = await ctx.x509.getPublicKey({ certificate: x5chain[0], algorithm })\n if (!key) {\n throw new NoPublicKeySetOnStatusListError()\n }\n\n return { chain, key }\n}\n\nexport type VerifyStatusListTokenOptions = {\n statusListInfo: Pick<StatusListInfo, 'uri' | 'idx'>\n /**\n * Trust anchors for the certificate chain of the list signer. Required unless\n * `disableCertificateChainValidation` is set.\n */\n trustedCertificates?: Array<Uint8Array>\n /**\n * Verify the list with the key of the leaf of its x5chain, without validating the chain.\n */\n disableCertificateChainValidation?: boolean\n now?: Date\n skewSeconds?: number\n checkFreshness?: boolean\n}\n\nexport type VerifyStatusListTokenResult = {\n statusListCwt: StatusListCwt\n /** The validated certificate chain of the list signer, leaf first. Not set without chain validation. */\n chain?: Array<Uint8Array>\n}\n\n/**\n * Fetch and verify the status list a `StatusListInfo` points at.\n *\n * `@owf/token-status-list` owns everything status-list-shaped — fetching and content-type\n * negotiation, the CWT structure, the claim checks and reading a status by index. What lives here\n * is only what that library cannot know about: the mdoc trust anchors and the `MdocContext` crypto\n * callbacks used to establish the signer, and the two rules ISO/IEC 18013-5 § 12.3.6 layers on top\n * of the Token Status List defaults — a mandatory `exp` (§ 12.3.6.3), and `Valid` as the only\n * acceptable status, since § 12.3.6.1 allows \"no other status besides 'revoked'\".\n *\n * § 12.3.6.3 requires the list to be a Status List Token \"in CWT format, since the IssuerAuth\n * structure is a CWT\", so a list served as a JWT is rejected rather than verified.\n */\nexport async function verifyStatusListToken(\n {\n statusListInfo,\n trustedCertificates,\n disableCertificateChainValidation,\n now = new Date(),\n skewSeconds,\n checkFreshness,\n }: VerifyStatusListTokenOptions,\n ctx: Pick<MdocContext, 'fetch' | 'x509' | 'cose'>\n): Promise<VerifyStatusListTokenResult> {\n if (!disableCertificateChainValidation) assertTrustedCertificates({ trustedCertificates })\n\n const { uri, idx } = statusListInfo\n const token = await fetchStatusList({ uri, customFetcher: ctx.fetch, acceptedFormats: ['cwt'] })\n\n // `fetchStatusList` decides on the response's Content-Type, not on `acceptedFormats`, so a JWT\n // still comes back as a string even though it was not asked for.\n if (typeof token === 'string') {\n throw new JwtNotSupportForStatusListError(\n `The status list at ${uri} was served in JWT format. ISO/IEC 18013-5 § 12.3.6.3 requires a Status List Token in CWT format, which is the only format @owf/mdoc verifies`\n )\n }\n\n const statusListCwt = StatusListCwt.fromToken(token)\n\n const x5chain = normalizeX5Chain(statusListCwt.protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.X5Chain))\n if (!x5chain) {\n throw new UnableToExtractX5ChainFromCwtError()\n }\n\n const { chain, key } = await verifyRevocationListSigner(\n {\n x5chain,\n algorithm: statusListCwt.algorithm as SignatureAlgorithm | undefined,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n },\n ctx\n )\n\n // Signature, claims and the status at `idx`, in one call: the token is only the issuer's if it\n // verifies, so there is nothing to read from it before that.\n await asMdlRevocationListError(\n () =>\n statusListCwt.verify(\n {\n key,\n uri,\n idx,\n now,\n skewSeconds,\n checkIssuedAt: checkFreshness,\n // § 12.3.6.3: \"The exp claim shall be present.\" OPTIONAL in the Token Status List\n // specification, which is why it is required here rather than there.\n requiredClaims: [RegisteredCwtClaimKey.ExpirationTime],\n },\n { sign1: ctx.cose.sign1 }\n ),\n InvalidSignatureError\n )\n\n return { statusListCwt, chain }\n}\n\nexport type VerifyIdentifierListTokenOptions = {\n identifierListInfo: Pick<IdentifierListInfo, 'uri' | 'id'>\n /**\n * Trust anchors for the certificate chain of the list signer. Required unless\n * `disableCertificateChainValidation` is set.\n */\n trustedCertificates?: Array<Uint8Array>\n /**\n * Verify the list with the key of the leaf of its x5chain, without validating the chain.\n */\n disableCertificateChainValidation?: boolean\n now?: Date\n skewSeconds?: number\n checkFreshness?: boolean\n}\n\nexport type VerifyIdentifierListTokenResult = {\n identifierListCwt: IdentifierListCwt\n /** The validated certificate chain of the list signer, leaf first. Not set without chain validation. */\n chain?: Array<Uint8Array>\n}\n\n/**\n * Fetch and verify the identifier list an `IdentifierListInfo` points at (§ 12.3.6.4):\n * certificate chain, signature, the claim checks § 12.3.6.1 makes binding on both revocation\n * mechanisms, and finally whether the MSO's own identifier appears in it — presence means revoked.\n *\n * The counterpart of {@link verifyStatusListToken}. Unlike a status list, the identifier list is an\n * ISO addition that the Token Status List specification does not describe, so `IdentifierListCwt`\n * lives in this package rather than in `@owf/token-status-list` — built on the same `Cwt`, so the\n * two are verified the same way.\n */\nexport async function verifyIdentifierListToken(\n {\n identifierListInfo,\n trustedCertificates,\n disableCertificateChainValidation,\n now = new Date(),\n skewSeconds,\n checkFreshness,\n }: VerifyIdentifierListTokenOptions,\n ctx: Pick<MdocContext, 'fetch' | 'x509' | 'cose'>\n): Promise<VerifyIdentifierListTokenResult> {\n if (!disableCertificateChainValidation) assertTrustedCertificates({ trustedCertificates })\n\n const { uri, id } = identifierListInfo\n const identifierListCwt = await IdentifierListCwt.fetch(uri, ctx)\n\n const x5chain = identifierListCwt.x5chain\n if (!x5chain || x5chain.length === 0) {\n throw new UnableToExtractX5ChainFromIdentifierListError()\n }\n\n const { chain, key } = await verifyRevocationListSigner(\n {\n x5chain,\n algorithm: identifierListCwt.algorithm as SignatureAlgorithm | undefined,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n },\n ctx\n )\n\n await asMdlRevocationListError(\n () =>\n identifierListCwt.verify(\n { key, uri, id, now, skewSeconds, checkIssuedAt: checkFreshness },\n { sign1: ctx.cose.sign1 }\n ),\n InvalidIdentifierListSignatureError\n )\n\n return { identifierListCwt, chain }\n}\n\n/** COSE_X509 carries either a single certificate or a chain of them (RFC 9360). */\nfunction normalizeX5Chain(x5chain: unknown): Array<Uint8Array> | undefined {\n const chain = x5chain instanceof Uint8Array ? [x5chain] : x5chain\n if (!Array.isArray(chain) || chain.length === 0 || !chain.every((c) => c instanceof Uint8Array)) return undefined\n return chain\n}\n","import {\n CosePayloadMustBeDefinedError,\n cborDecode,\n DataItem,\n Sign1,\n type Sign1EncodedStructure,\n type Sign1Options,\n zUint8Array,\n} from '@owf/cose'\nimport { compareBytes } from '@owf/identity-common'\nimport type { 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 type { IdentifierListCwt } from './identifier-list-cwt'\nimport { MobileSecurityObject, type MobileSecurityObjectEncodedStructure } from './mobile-security-object.js'\nimport { verifyIdentifierListToken, verifyStatusListToken } from './mso-revocation-list'\n\nexport type IssuerAuthEncodedStructure = Sign1EncodedStructure\nexport type IssuerAuthOptions = Omit<Sign1Options, 'payload'> & {\n payload?: Sign1Options['payload'] | MobileSecurityObject\n}\n\nexport type IssuerAuthVerificationResult = {\n /**\n * The certificate chain of the document signer up to a trusted certificate. Undefined when\n * certificate chain validation is disabled, or when it failed and the verification callback did not throw.\n */\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 // biome-ignore lint/complexity/noThisInStatic: `super.create` keeps `this` bound to the subclass\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 /**\n * The `countryName` in the subject of the document signer certificate, which `issuing_country` must\n * match (18013-5 7.2.1).\n */\n public getIssuingCountry(ctx: Pick<MdocContext, 'x509'>) {\n return ctx.x509.getSubjectNameField({ certificate: this.certificate, field: 'C' })[0]\n }\n\n /**\n * The `stateOrProvinceName` in the subject of the document signer certificate, if present, which\n * `issuing_jurisdiction` must match (18013-5 7.2.1).\n */\n public getIssuingStateOrProvince(ctx: Pick<MdocContext, 'x509'>) {\n return ctx.x509.getSubjectNameField({ certificate: this.certificate, field: 'ST' })[0]\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 skewSeconds,\n checkFreshness,\n trustedStatusCertificates,\n disableCertificateChainValidation,\n }: {\n now?: Date\n /** Tolerance applied to the `exp` and `iat` of a revocation list. Defaults to 30 seconds. */\n skewSeconds?: number\n checkFreshness?: boolean\n trustedStatusCertificates?: Uint8Array[]\n /**\n * Verify a revocation list with the key of the leaf of its x5chain, without validating its\n * certificate chain against `trustedStatusCertificates`. The revocation status is still checked.\n */\n disableCertificateChainValidation?: boolean\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 const statusListResult = status.statusList\n ? await verifyStatusListToken(\n {\n statusListInfo: status.statusList,\n trustedCertificates: trustedStatusCertificates,\n disableCertificateChainValidation,\n now,\n skewSeconds,\n checkFreshness,\n },\n ctx\n )\n : undefined\n\n const identifierListResult = status.identifierList\n ? await verifyIdentifierListToken(\n {\n identifierListInfo: status.identifierList,\n trustedCertificates: trustedStatusCertificates,\n disableCertificateChainValidation,\n now,\n skewSeconds,\n checkFreshness,\n },\n ctx\n )\n : undefined\n\n return {\n statusList: statusListResult?.statusListCwt,\n trustedStatusListChain: statusListResult?.chain,\n identifierList: identifierListResult?.identifierListCwt,\n trustedIdentifierListChain: identifierListResult?.chain,\n }\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 // Status information is trusted when it is signed by a status certificate of the trust anchor\n // the issuance chain ends in.\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 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 let statusList: StatusListCwt | undefined\n let trustedStatusListChain: Uint8Array[] | undefined\n let identifierList: IdentifierListCwt | undefined\n let trustedIdentifierListChain: Uint8Array[] | undefined\n // The revocation list URIs come from the MSO, so they are only fetched once the MSO is known to be\n // signed by the issuer. A forged MSO must not make the verifier request a URI of its choosing.\n if (!disableStatusValidation && isSignatureValid) {\n try {\n ;({ statusList, trustedStatusListChain, identifierList, trustedIdentifierListChain } = await this.verifyStatus(\n {\n now,\n skewSeconds,\n checkFreshness: true,\n trustedStatusCertificates,\n // Without chain validation there is no trust anchor to take the status certificates from,\n // so the chains of the revocation lists are not validated either.\n disableCertificateChainValidation,\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 { 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()}); its validity period is ${validityInfo.validFrom.toUTCString()} to ${validityInfo.validUntil.toUTCString()} (allowed clock skew ${skewSeconds}s)`,\n })\n\n if (!disableCertificateChainValidation) {\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\n return {\n trustedIssuanceChain,\n statusList,\n trustedStatusListChain,\n identifierList,\n trustedIdentifierListChain,\n }\n }\n}\n","import { typedMap, zUint8Array } from '@owf/cose'\nimport { compareBytes } from '@owf/identity-common'\nimport { z } from 'zod'\nimport type { MdocContext } from '../../context'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\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\n/**\n * Decoded items keep the `IssuerSignedItemBytes` they were received as, as the digests in the MSO are\n * computed over them.\n */\nexport class IssuerSignedItem extends OriginalBytesCborStructure<\n IssuerSignedItemEncodedStructure,\n IssuerSignedItemDecodedStructure\n> {\n public static override get encodingSchema() {\n return issuerSignedItemSchema\n }\n\n /**\n * @deprecated Use {@link originalBytes}.\n */\n public get originalPayloadBytes() {\n return this.originalBytes\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 // 18013-5 7.2.1: the check \"is only required if the stateOrProvinceName element is present in the DS\n // certificate\".\n if (this.elementIdentifier === 'issuing_jurisdiction') {\n const stateOrProvince = issuerAuth.getIssuingStateOrProvince(ctx)\n return stateOrProvince === undefined || this.elementValue === stateOrProvince\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 // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\n return this.fromEncodedStructure(map)\n }\n}\n","import { CborStructure, DataItem } from '@owf/cose'\nimport z from 'zod'\nimport { IssuerSignedItem } 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.fromDataItem(isi))\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 // Forward the issuer's own bytes for items we received rather than built. A\n // verifier digests the IssuerSignedItemBytes it is given and compares that to\n // valueDigests, so re-encoding from the decoded structure breaks the digest for\n // any issuer whose encoder differs from ours.\n value.map((isi) => isi.asDataItem)\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(options.issuerNamespaces)\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\n// 18013-5 8.3.2.1.2.2: `nameSpaces` is optional, and left out when no issuer-signed element is\n// disclosed, as `IssuerNameSpaces` must have at least one namespace.\nconst issuerSignedSchema = typedMap([\n ['nameSpaces', z.instanceof(IssuerNamespaces).exactOptional()],\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 if (input.has('nameSpaces')) {\n map.set(\n 'nameSpaces',\n IssuerNamespaces.fromEncodedStructure(input.get('nameSpaces') as IssuerNamespacesEncodedStructure)\n )\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 const nameSpaces = output.get('nameSpaces')\n if (nameSpaces !== undefined) map.set('nameSpaces', 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 Object.fromEntries(issuerSignedItems.map((item) => [item.elementIdentifier, item.elementValue]))\n }\n\n public get encodedForOid4Vci() {\n return base64url.encode(this.encode())\n }\n\n public static fromEncodedForOid4Vci(encoded: string): IssuerSigned {\n // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\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 // 18013-5 8.3.2.1.2.2: the mdoc shall not include two or more IssuerSignedItem elements with\n // the same element identifier in a single namespace and document.\n const elementIdentifiers = nsItems.map((item) => item.elementIdentifier)\n const duplicates = new Set(elementIdentifiers.filter((id, index) => elementIdentifiers.indexOf(id) !== index))\n onCheck({\n status: duplicates.size === 0 ? 'PASSED' : 'FAILED',\n check: `Namespace ${ns} must not include multiple elements with the same element identifier`,\n reason: duplicates.size\n ? `Namespace ${ns} includes multiple elements for ${Array.from(duplicates)\n .map((id) => `'${id}'`)\n .join(', ')}`\n : undefined,\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import type { VerificationCallback } from '../mdoc/check-callback'\nimport { InvalidDeviceRequestMatchOptionsError } from '../mdoc/errors'\nimport type { DataElementIdentifier } from '../mdoc/models/data-element-identifier'\nimport type { DataElementValue } from '../mdoc/models/data-element-value'\nimport type { DeviceNamespaces } from '../mdoc/models/device-namespaces'\nimport type { DeviceRequest } from '../mdoc/models/device-request'\nimport type { DeviceResponse } from '../mdoc/models/device-response'\nimport type { DocType } from '../mdoc/models/doctype'\nimport type { IntentToRetain } from '../mdoc/models/intent-to-retain'\nimport { IssuerSigned } from '../mdoc/models/issuer-signed'\nimport type { IssuerSignedItem } from '../mdoc/models/issuer-signed-item'\nimport type { KeyAuthorizations } from '../mdoc/models/key-authorizations'\nimport type { Namespace } from '../mdoc/models/namespace'\nimport { describeAgeOverLimitViolations, findAgeOverCandidate, findAgeOverRequestLimitViolations } from './ageOver'\nimport { getOwnProperty } from './getOwnProperty'\nimport { isDeviceSignedElementAuthorized } from './keyAuthorizations'\n\nexport type DisclosedElementSource = 'issuerSigned' | 'deviceSigned'\n\nexport type DisclosedElement = {\n namespace: Namespace\n elementIdentifier: DataElementIdentifier\n elementValue: DataElementValue\n source: DisclosedElementSource\n}\n\n/**\n * How a single requested element is matched. An `ItemsRequest` can express neither that an element\n * is optional nor where it is expected to come from, so the verifier — which built the request —\n * provides it as context to the match.\n */\nexport type ElementMatchOptions = {\n /**\n * Whether the response may leave this element out without failing the match. An optional element\n * never makes a document fail, but it is still reported per claim. Defaults to `false`.\n */\n optional?: boolean\n\n /**\n * Where the element may be disclosed from. Device-signed elements are asserted by the mdoc\n * itself and not by the issuer, so an element the issuer is expected to attest to, an\n * `age_over_NN` for instance, must not be answered from `deviceSigned`. Defaults to\n * `'issuerSigned'`.\n *\n * Even if `'deviceSigned'` is allowed, the element must be in the key authorizations of the mdoc.\n */\n source?: DisclosedElementSource | 'any'\n}\n\nexport type DocRequestMatchOptions = {\n /**\n * Index into `deviceRequest.docRequests` of the doc request these options apply to.\n */\n docRequestIndex: number\n\n /**\n * Per-element match options, keyed by namespace and element identifier. The element identifier\n * `'*'` applies to every element in the namespace that is not named explicitly, which is how a\n * namespace that is entirely device-signed is described.\n *\n * ```ts\n * {\n * 'org.iso.18013.5.1': { portrait: { optional: true } },\n * 'com.example.device': { '*': { source: 'deviceSigned' } },\n * }\n * ```\n */\n elements?: Record<Namespace, Record<DataElementIdentifier, ElementMatchOptions>>\n}\n\n/**\n * Per doc request the elements that are optional or that may be answered from `deviceSigned`. By\n * default every requested element is required and must be issuer-signed.\n */\nexport type DeviceRequestMatchOptions = {\n /**\n * A doc request can have options at most once.\n */\n docRequests?: Array<DocRequestMatchOptions>\n\n /**\n * A device request with more than one doc request does not say whether it asks for all of them, or\n * for any one of them. By default every doc request has to be satisfied. Set this to treat them as\n * alternatives instead, of which at least one has to be satisfied, which is a common\n * interpretation. The second edition of 18013-5 resolves the ambiguity with use cases in\n * `DeviceRequestInfo`, which are not supported yet.\n *\n * Does not apply to a device request with a single doc request. Defaults to `false`.\n */\n treatAmbiguousMultipleDocRequestsAsAlternatives?: boolean\n}\n\nexport type ClaimMatchBase = {\n namespace: Namespace\n /**\n * The element identifier as it appears in the `ItemsRequest`.\n */\n elementIdentifier: DataElementIdentifier\n intentToRetain: IntentToRetain\n /**\n * Whether the element was matched as optional, and therefore cannot make the claims fail. Always\n * `false` when matching the credentials of a holder, as the request does not say which elements\n * are optional.\n */\n optional: boolean\n}\n\nexport type ClaimMatchSuccess = ClaimMatchBase & {\n success: true\n /**\n * The element identifier that is disclosed. Only differs from `elementIdentifier` when an\n * `age_over_NN` request is answered with a different age attestation (18013-5 7.2.5).\n */\n disclosedElementIdentifier: DataElementIdentifier\n elementValue: DataElementValue\n source: DisclosedElementSource\n}\n\nexport type ClaimMatchFailure = ClaimMatchBase & {\n success: false\n /**\n * `'notDisclosed'` — the document did not disclose the element, or the credential cannot: the\n * issuer did not sign it, and either the device key is not authorized for it or no value was\n * provided for it in the device namespaces.\n *\n * `'disallowedSource'` — the document did disclose it, but only from a source the match options\n * do not allow for this element. By default only `issuerSigned` is allowed, so a `deviceSigned`\n * element the verifier did not mark as device-signed fails here rather than counting as a match.\n *\n * `'deviceKeyNotAuthorized'` — the document did disclose it device-signed, from a source the match\n * options allow, but the device key is not authorized for it in the key authorizations of the MSO\n * (18013-5 9.1.3.4).\n */\n failure: 'notDisclosed' | 'disallowedSource' | 'deviceKeyNotAuthorized'\n /**\n * The source the element was disclosed from, when `failure` is `'disallowedSource'` or\n * `'deviceKeyNotAuthorized'`.\n */\n disclosedFrom?: DisclosedElementSource\n reason: string\n}\n\nexport type ClaimMatch = ClaimMatchSuccess | ClaimMatchFailure\n\ntype NonEmptyArray<T> = [T, ...Array<T>]\n\nexport type DocTypeMatchSuccess = {\n success: true\n docType: DocType\n}\n\nexport type DocTypeMatchFailure = {\n success: false\n /**\n * The docType of the document or credential.\n */\n docType: DocType\n reason: string\n}\n\n/**\n * Whether a document or credential has the docType the doc request asks for.\n */\nexport type DocTypeMatchResult = DocTypeMatchSuccess | DocTypeMatchFailure\n\n/**\n * Every requested element that is not optional is disclosed.\n */\nexport type ClaimsMatchSuccess = {\n success: true\n /**\n * The requested elements that are disclosed, in request order.\n */\n validClaims: Array<ClaimMatchSuccess>\n /**\n * The optional requested elements that are not disclosed, in request order.\n */\n failedClaims: Array<ClaimMatchFailure & { optional: true }>\n}\n\n/**\n * At least one requested element that is not optional is not disclosed.\n */\nexport type ClaimsMatchFailure = {\n success: false\n /**\n * The requested elements that are disclosed, in request order.\n */\n validClaims: Array<ClaimMatchSuccess>\n /**\n * The requested elements that are not disclosed, in request order. Can contain optional elements.\n */\n failedClaims: NonEmptyArray<ClaimMatchFailure>\n}\n\nexport type ClaimsMatchResult = ClaimsMatchSuccess | ClaimsMatchFailure\n\ntype UnrequestedClaims = {\n /**\n * Elements the document disclosed that the doc request did not ask for. Not a failure by itself\n * — it is the mdoc over-disclosing — but a verifier should not process data it did not request.\n */\n unrequestedClaims: Array<DisclosedElement>\n}\n\nexport type DocumentClaimsMatchSuccess = ClaimsMatchSuccess & UnrequestedClaims\nexport type DocumentClaimsMatchFailure = ClaimsMatchFailure & UnrequestedClaims\nexport type DocumentClaimsMatchResult = DocumentClaimsMatchSuccess | DocumentClaimsMatchFailure\n\ntype DocumentMatchBase = {\n /**\n * Index into `deviceResponse.documents` of the document this result is about.\n */\n documentIndex: number\n}\n\nexport type DocumentMatchSuccess = DocumentMatchBase & {\n success: true\n docType: DocTypeMatchSuccess\n claims: DocumentClaimsMatchSuccess\n}\n\nexport type DocumentMatchFailure = DocumentMatchBase & {\n success: false\n docType: DocTypeMatchResult\n claims: DocumentClaimsMatchResult\n}\n\n/**\n * Whether a document satisfies a doc request. The `docType` check requires both the docType of the\n * document and the docType of its mobile security object to be the requested docType: the docType\n * outside the MSO is not signed.\n */\nexport type DocumentMatch = DocumentMatchSuccess | DocumentMatchFailure\n\ntype DocRequestMatchBase = {\n /**\n * Index into `deviceRequest.docRequests` of the doc request this result is about.\n */\n docRequestIndex: number\n docType: DocType\n /**\n * The documents that do not satisfy this doc request, in response order. This includes every\n * document of another docType, for which the `docType` check failed.\n */\n failedDocuments: Array<DocumentMatchFailure>\n}\n\nexport type DocRequestMatchSuccess = DocRequestMatchBase & {\n success: true\n /**\n * The documents that satisfy this doc request, in response order.\n */\n validDocuments: NonEmptyArray<DocumentMatchSuccess>\n}\n\nexport type DocRequestMatchFailure = DocRequestMatchBase & {\n success: false\n validDocuments: []\n}\n\nexport type DocRequestMatch = DocRequestMatchSuccess | DocRequestMatchFailure\n\ntype DocRequestsAsAlternatives = {\n /**\n * Whether the doc requests were matched as alternatives, of which at least one has to be\n * satisfied, rather than all of them. Only `true` when\n * `treatAmbiguousMultipleDocRequestsAsAlternatives` is set and the device request has more than\n * one doc request.\n */\n docRequestsAsAlternatives: boolean\n}\n\ntype DeviceRequestMatchBase = DocRequestsAsAlternatives & {\n /**\n * Documents in the response whose docType no doc request asked for.\n */\n unrequestedDocuments: Array<{ documentIndex: number; docType: DocType }>\n}\n\n/**\n * Every doc request is satisfied or, when matched as alternatives, at least one of them.\n */\nexport type DeviceRequestMatchSuccess = DeviceRequestMatchBase &\n (\n | {\n success: true\n docRequestsAsAlternatives: false\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<DocRequestMatchSuccess>\n }\n | {\n success: true\n docRequestsAsAlternatives: true\n /**\n * One entry per doc request, in request order. At least one is successful.\n */\n docRequests: Array<DocRequestMatch>\n }\n )\n\nexport type DeviceRequestMatchFailure = DeviceRequestMatchBase & {\n success: false\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<DocRequestMatch>\n}\n\nexport type DeviceRequestMatchResult = DeviceRequestMatchSuccess | DeviceRequestMatchFailure\n\ntype CredentialMatchBase = {\n /**\n * Index into `credentials` of the credential this result is about.\n */\n credentialIndex: number\n}\n\nexport type CredentialMatchSuccess = CredentialMatchBase & {\n success: true\n docType: DocTypeMatchSuccess\n claims: ClaimsMatchSuccess\n}\n\nexport type CredentialMatchFailure = CredentialMatchBase & {\n success: false\n docType: DocTypeMatchResult\n claims: ClaimsMatchResult\n}\n\n/**\n * Whether a credential can satisfy a doc request. The `docType` check requires the docType of the\n * mobile security object of the credential to be the requested docType.\n */\nexport type CredentialMatch = CredentialMatchSuccess | CredentialMatchFailure\n\ntype HolderDocRequestMatchBase = {\n /**\n * Index into `deviceRequest.docRequests` of the doc request this result is about.\n */\n docRequestIndex: number\n docType: DocType\n /**\n * The credentials that do not satisfy this doc request, in the order they were provided. This\n * includes every credential of another docType, for which the `docType` check failed. Empty when\n * the doc request is invalid, as credentials are then not matched.\n */\n failedCredentials: Array<CredentialMatchFailure>\n}\n\nexport type HolderDocRequestMatchSuccess = HolderDocRequestMatchBase & {\n success: true\n /**\n * The credentials that satisfy this doc request, in the order they were provided.\n */\n validCredentials: NonEmptyArray<CredentialMatchSuccess>\n}\n\n/**\n * Why a doc request cannot be answered by any credential.\n *\n * `'ageOverLimitExceeded'` — the doc request asks for more than two `age_over_NN` elements in a\n * namespace, which 18013-5 7.2.5 forbids a reader to do, as together they narrow down the age of\n * the holder.\n */\nexport type InvalidDocRequest = {\n failure: 'ageOverLimitExceeded'\n reason: string\n}\n\nexport type HolderDocRequestMatchFailure = HolderDocRequestMatchBase & {\n success: false\n validCredentials: []\n /**\n * Set when the doc request itself is invalid. No credential is then matched against it, so\n * `failedCredentials` is empty.\n */\n invalidDocRequest?: InvalidDocRequest\n}\n\nexport type HolderDocRequestMatch = HolderDocRequestMatchSuccess | HolderDocRequestMatchFailure\n\n/**\n * Every doc request can be answered or, when matched as alternatives, at least one of them.\n */\nexport type HolderDeviceRequestMatchSuccess =\n | {\n success: true\n docRequestsAsAlternatives: false\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<HolderDocRequestMatchSuccess>\n }\n | {\n success: true\n docRequestsAsAlternatives: true\n /**\n * One entry per doc request, in request order. At least one is successful.\n */\n docRequests: Array<HolderDocRequestMatch>\n }\n\nexport type HolderDeviceRequestMatchFailure = DocRequestsAsAlternatives & {\n success: false\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<HolderDocRequestMatch>\n}\n\nexport type HolderDeviceRequestMatchResult = HolderDeviceRequestMatchSuccess | HolderDeviceRequestMatchFailure\n\n/**\n * A credential of the holder, with the values the holder can disclose device-signed for it.\n */\nexport type HolderCredential = {\n issuerSigned: IssuerSigned\n /**\n * The values the holder can disclose device-signed with this credential. A requested element the\n * issuer did not sign only matches when its value is here and the device key is authorized for\n * it, the same as when creating the response.\n */\n deviceNamespaces?: DeviceNamespaces\n}\n\n/**\n * Match a `DeviceResponse` against the `DeviceRequest` it answers (verifier side).\n *\n * The ISO mdoc DC API protocol (`org-iso-mdoc`) has no query language such as DCQL that describes\n * which claims a response has to contain, so this walks the device request itself and reports, per\n * doc request, per document and per check whether the response satisfies it.\n *\n * An element only counts as disclosed when it comes from `issuerSigned`, as `deviceSigned` elements\n * are asserted by the mdoc itself rather than by the issuer. Pass `matchOptions` to mark elements\n * that are optional or that are expected to be device-signed.\n *\n * By default the match only succeeds when every doc request is satisfied. Set\n * `treatAmbiguousMultipleDocRequestsAsAlternatives` in `matchOptions` to have it succeed when at\n * least one is.\n *\n * Shares its matching with {@link matchCredentialsToDeviceRequest}, which matches like a verifier\n * that accepts every element from `'any'` source.\n *\n * This is purely a structural comparison — it does not verify issuer auth, device auth or the\n * digests of the disclosed elements. Use it alongside `DeviceResponse.verify`, which runs it as\n * part of verification when a `deviceRequest` is passed.\n */\nexport const matchDeviceRequest = (options: {\n deviceRequest: DeviceRequest\n deviceResponse: DeviceResponse\n matchOptions?: DeviceRequestMatchOptions\n}): DeviceRequestMatchResult => {\n const { deviceRequest, deviceResponse, matchOptions } = options\n const docRequestOptions = indexDocRequestOptions(deviceRequest, matchOptions)\n\n // Every access to the mobile security object decodes it, so decode it once per document.\n const documents = (deviceResponse.documents ?? []).map((document) => ({\n document,\n mobileSecurityObject: document.issuerSigned.issuerAuth.mobileSecurityObject,\n }))\n\n const docRequests = deviceRequest.docRequests.map((docRequest, docRequestIndex): DocRequestMatch => {\n const { docType, namespaces } = docRequest.itemsRequest\n const elements = docRequestOptions.get(docRequestIndex)?.elements\n\n const documentMatches = documents.map(({ document, mobileSecurityObject }, documentIndex): DocumentMatch => {\n const mobileSecurityObjectDocType = mobileSecurityObject.docType\n const docTypeResult: DocTypeMatchResult =\n document.docType !== docType\n ? {\n success: false,\n docType: document.docType,\n reason: `Document has docType '${document.docType}', but docType '${docType}' was requested`,\n }\n : mobileSecurityObjectDocType !== docType\n ? {\n success: false,\n docType: document.docType,\n reason: `Document has docType '${docType}', but the mobile security object has docType '${mobileSecurityObjectDocType}'`,\n }\n : { success: true, docType }\n\n const { claims, unusedElements } = matchElements({\n mode: 'verifier',\n namespaces,\n elements,\n issuerSigned: document.issuerSigned,\n keyAuthorizations: mobileSecurityObject.deviceKeyInfo.keyAuthorizations,\n deviceNamespaces: document.deviceSigned.deviceNamespaces,\n })\n const claimsResult: DocumentClaimsMatchResult = {\n ...toClaimsMatchResult(claims),\n unrequestedClaims: unusedElements,\n }\n\n return docTypeResult.success && claimsResult.success\n ? { documentIndex, success: true, docType: docTypeResult, claims: claimsResult }\n : { documentIndex, success: false, docType: docTypeResult, claims: claimsResult }\n })\n\n const validDocuments = documentMatches.filter((documentMatch) => documentMatch.success)\n const failedDocuments = documentMatches.filter((documentMatch) => !documentMatch.success)\n\n return isNonEmptyArray(validDocuments)\n ? { docRequestIndex, docType, success: true, validDocuments, failedDocuments }\n : { docRequestIndex, docType, success: false, validDocuments: [], failedDocuments }\n })\n\n const requestedDocTypes = new Set(deviceRequest.docRequests.map((docRequest) => docRequest.itemsRequest.docType))\n const unrequestedDocuments = documents.flatMap(({ document }, documentIndex) =>\n requestedDocTypes.has(document.docType) ? [] : [{ documentIndex, docType: document.docType }]\n )\n\n if (matchDocRequestsAsAlternatives(deviceRequest, matchOptions?.treatAmbiguousMultipleDocRequestsAsAlternatives)) {\n return docRequests.some((docRequest) => docRequest.success)\n ? { success: true, docRequestsAsAlternatives: true, docRequests, unrequestedDocuments }\n : { success: false, docRequestsAsAlternatives: true, docRequests, unrequestedDocuments }\n }\n\n return docRequests.every((docRequest) => docRequest.success)\n ? { success: true, docRequestsAsAlternatives: false, docRequests, unrequestedDocuments }\n : { success: false, docRequestsAsAlternatives: false, docRequests, unrequestedDocuments }\n}\n\n/**\n * Match the credentials of a holder against a `DeviceRequest` (holder side), to select which\n * credentials can answer which doc request.\n *\n * Reports per doc request, per credential and per check whether the credential satisfies the doc\n * request, so a holder can show which credentials match, and for a credential of the right docType\n * which requested elements it is missing. Every credential is matched against every doc request, and\n * is referred to by its index in `credentials`.\n *\n * A requested element is disclosed issuer-signed when the issuer signed it (or, for an\n * `age_over_NN` request, the age attestation 18013-5 7.2.5 allows in its place). Otherwise it is\n * disclosed device-signed when the credential comes with a value for exactly that element in its\n * `deviceNamespaces`, and the device key is authorized for it in the key authorizations of the MSO.\n *\n * `DeviceResponse.createWithDeviceRequest` selects the elements to disclose the same way, so a\n * credential that matches can answer the doc request with the same `deviceNamespaces`. The request\n * does not say which elements are optional, so every requested element is required.\n *\n * A doc request that asks for more than two `age_over_NN` elements in a namespace (18013-5 7.2.5)\n * is not matched against any credential, and fails with `invalidDocRequest`.\n *\n * By default the match only succeeds when every doc request can be answered. Pass\n * `treatAmbiguousMultipleDocRequestsAsAlternatives` to have it succeed when at least one can.\n *\n * Shares its matching with {@link matchDeviceRequest}: a credential matches like a verifier that\n * accepts every element from `'any'` source would match the response. A verifier only accepts\n * issuer-signed elements by default, so a device-signed element only satisfies it when its match\n * options allow `deviceSigned` for it.\n */\nexport const matchCredentialsToDeviceRequest = (options: {\n deviceRequest: DeviceRequest\n credentials: Array<IssuerSigned | HolderCredential>\n /**\n * See `DeviceRequestMatchOptions.treatAmbiguousMultipleDocRequestsAsAlternatives`. Defaults to\n * `false`.\n */\n treatAmbiguousMultipleDocRequestsAsAlternatives?: boolean\n}): HolderDeviceRequestMatchResult => {\n const { deviceRequest } = options\n const credentials = options.credentials.map((credential) => {\n const { issuerSigned, deviceNamespaces }: HolderCredential =\n credential instanceof IssuerSigned ? { issuerSigned: credential } : credential\n\n // Every access to the mobile security object decodes it, so decode it once per credential.\n return { issuerSigned, deviceNamespaces, mobileSecurityObject: issuerSigned.issuerAuth.mobileSecurityObject }\n })\n\n const docRequests = deviceRequest.docRequests.map((docRequest, docRequestIndex): HolderDocRequestMatch => {\n const { docType, namespaces } = docRequest.itemsRequest\n\n const ageOverLimitViolations = findAgeOverRequestLimitViolations(namespaces)\n if (ageOverLimitViolations.length > 0) {\n return {\n docRequestIndex,\n docType,\n success: false,\n validCredentials: [],\n failedCredentials: [],\n invalidDocRequest: {\n failure: 'ageOverLimitExceeded',\n reason: `Doc request ${docRequestIndex} requests ${describeAgeOverLimitViolations(ageOverLimitViolations)}, but at most two age_over_NN elements may be requested per namespace`,\n },\n }\n }\n\n const credentialMatches = credentials.map(\n ({ issuerSigned, deviceNamespaces, mobileSecurityObject }, credentialIndex): CredentialMatch => {\n const credentialDocType = mobileSecurityObject.docType\n const docTypeResult: DocTypeMatchResult =\n credentialDocType === docType\n ? { success: true, docType }\n : {\n success: false,\n docType: credentialDocType,\n reason: `Credential has docType '${credentialDocType}', but docType '${docType}' was requested`,\n }\n\n const claimsResult = toClaimsMatchResult(\n matchElements({\n mode: 'holder',\n namespaces,\n issuerSigned,\n keyAuthorizations: mobileSecurityObject.deviceKeyInfo.keyAuthorizations,\n deviceNamespaces,\n }).claims\n )\n\n return docTypeResult.success && claimsResult.success\n ? { credentialIndex, success: true, docType: docTypeResult, claims: claimsResult }\n : { credentialIndex, success: false, docType: docTypeResult, claims: claimsResult }\n }\n )\n\n const validCredentials = credentialMatches.filter((credentialMatch) => credentialMatch.success)\n const failedCredentials = credentialMatches.filter((credentialMatch) => !credentialMatch.success)\n\n return isNonEmptyArray(validCredentials)\n ? { docRequestIndex, docType, success: true, validCredentials, failedCredentials }\n : { docRequestIndex, docType, success: false, validCredentials: [], failedCredentials }\n })\n\n if (matchDocRequestsAsAlternatives(deviceRequest, options.treatAmbiguousMultipleDocRequestsAsAlternatives)) {\n return docRequests.some((docRequest) => docRequest.success)\n ? { success: true, docRequestsAsAlternatives: true, docRequests }\n : { success: false, docRequestsAsAlternatives: true, docRequests }\n }\n\n return docRequests.every((docRequest) => docRequest.success)\n ? { success: true, docRequestsAsAlternatives: false, docRequests }\n : { success: false, docRequestsAsAlternatives: false, docRequests }\n}\n\n/**\n * Whether the doc requests are matched as alternatives. A single doc request is not ambiguous, so it\n * always has to be satisfied.\n */\nconst matchDocRequestsAsAlternatives = (\n deviceRequest: DeviceRequest,\n treatAmbiguousMultipleDocRequestsAsAlternatives = false\n) => treatAmbiguousMultipleDocRequestsAsAlternatives && deviceRequest.docRequests.length > 1\n\ntype ElementCandidate = DisclosedElement & {\n /**\n * The issuer-signed item the element comes from, so a holder can disclose it as is.\n */\n issuerSignedItem?: IssuerSignedItem\n}\n\n/**\n * @internal\n */\nexport type ElementMatch =\n | {\n claim: ClaimMatchSuccess\n element: ElementCandidate\n }\n | { claim: ClaimMatchFailure; element?: undefined }\n\n/**\n * Match the requested elements of a single doc request against a single document or credential.\n * Shared by the verifier and the holder side.\n *\n * - `verifier` matches the elements a document disclosed, from the source the `elements` options\n * allow (by default `issuerSigned`).\n * - `holder` matches the elements a credential can disclose: issuer-signed when the issuer signed\n * it, and otherwise device-signed when `deviceNamespaces` has a value for exactly that element.\n * Device-signed values are provided by the holder itself, so an `age_over_NN` request is not\n * answered with a device-signed value for another age.\n *\n * Either way a device-signed element only answers a request when the device key is authorized for\n * it (18013-5 9.1.3.4).\n *\n * @internal\n */\nexport const matchElements = (options: {\n mode: 'holder' | 'verifier'\n namespaces: Map<Namespace, Map<DataElementIdentifier, IntentToRetain>>\n elements?: Record<Namespace, Record<DataElementIdentifier, ElementMatchOptions>>\n issuerSigned: IssuerSigned\n /**\n * The key authorizations in the mobile security object of `issuerSigned`, passed in so that the\n * caller decodes the mobile security object only once.\n */\n keyAuthorizations: KeyAuthorizations | undefined\n deviceNamespaces?: DeviceNamespaces\n}): { claims: Array<ElementMatch>; unusedElements: Array<DisclosedElement> } => {\n const { mode, namespaces, keyAuthorizations } = options\n\n const available = collectElements(options.issuerSigned, options.deviceNamespaces)\n\n const claims: Array<ElementMatch> = []\n const usedElements = new Set<DisclosedElement>()\n\n const success = (claim: ClaimMatchBase, element: ElementCandidate) => {\n usedElements.add(element)\n claims.push({\n element,\n claim: {\n ...claim,\n success: true,\n disclosedElementIdentifier: element.elementIdentifier,\n elementValue: element.elementValue,\n source: element.source,\n },\n })\n }\n\n const failure = (\n claim: ClaimMatchBase,\n failure: Pick<ClaimMatchFailure, 'failure' | 'disclosedFrom' | 'reason'>,\n // The elements the document disclosed for the claim, so they are not also reported as unrequested.\n ...disclosed: Array<ElementCandidate | undefined>\n ) => {\n for (const element of disclosed) if (element) usedElements.add(element)\n claims.push({ claim: { ...claim, success: false, ...failure } })\n }\n\n for (const [namespace, requestedElements] of namespaces) {\n const issuerSignedInNamespace = available.filter(\n (element) => element.namespace === namespace && element.source === 'issuerSigned'\n )\n const deviceSignedInNamespace = available.filter(\n (element) => element.namespace === namespace && element.source === 'deviceSigned'\n )\n // 18013-5 9.1.3.4: device-signed elements only answer a request when the device key is\n // authorized for them.\n const authorizedDeviceSignedInNamespace = deviceSignedInNamespace.filter((element) =>\n isDeviceSignedElementAuthorized(keyAuthorizations, element)\n )\n const namespaceOptions = getOwnProperty(options.elements, namespace)\n\n for (const [elementIdentifier, intentToRetain] of requestedElements) {\n if (mode === 'holder') {\n const claim = { namespace, elementIdentifier, intentToRetain, optional: false }\n\n const element =\n findElement(elementIdentifier, issuerSignedInNamespace) ??\n authorizedDeviceSignedInNamespace.find((candidate) => candidate.elementIdentifier === elementIdentifier)\n if (element) {\n success(claim, element)\n continue\n }\n\n failure(claim, {\n failure: 'notDisclosed',\n reason: isDeviceSignedElementAuthorized(keyAuthorizations, { namespace, elementIdentifier })\n ? `Element '${elementIdentifier}' in namespace '${namespace}' is not issuer-signed in the credential, so it has to be disclosed device-signed, but no value was provided for it in the device namespaces`\n : `Element '${elementIdentifier}' in namespace '${namespace}' is not issuer-signed in the credential, and the device key is not authorized to sign it`,\n })\n continue\n }\n\n const { optional = false, source = 'issuerSigned' } =\n getOwnProperty(namespaceOptions, elementIdentifier) ?? getOwnProperty(namespaceOptions, '*') ?? {}\n const claim = { namespace, elementIdentifier, intentToRetain, optional }\n\n // The source is applied before the element is picked, so that an `age_over_NN` request is not\n // answered by a device-signed attestation while an issuer-signed one is also present.\n const element =\n source === 'deviceSigned'\n ? findElement(elementIdentifier, authorizedDeviceSignedInNamespace)\n : (findElement(elementIdentifier, issuerSignedInNamespace) ??\n (source === 'any' ? findElement(elementIdentifier, authorizedDeviceSignedInNamespace) : undefined))\n\n if (element) {\n success(claim, element)\n continue\n }\n\n // The element may still be there, just not in a way this verifier accepts for it — report\n // that rather than letting it pass or reporting it as absent. Both are marked as used, as the\n // doc request did ask for the element.\n //\n // Disclosed from a source that is not allowed:\n const disallowed =\n source === 'any'\n ? undefined\n : findElement(\n elementIdentifier,\n source === 'issuerSigned' ? deviceSignedInNamespace : issuerSignedInNamespace\n )\n // Disclosed device-signed from an allowed source, but every authorized element was already\n // tried above:\n const unauthorized =\n source === 'issuerSigned' ? undefined : findElement(elementIdentifier, deviceSignedInNamespace)\n\n // The unauthorized element is the one disclosed from the allowed source, so it is the failure\n // to report when both are there.\n if (unauthorized) {\n failure(\n claim,\n {\n failure: 'deviceKeyNotAuthorized',\n disclosedFrom: 'deviceSigned',\n reason: `Element '${unauthorized.elementIdentifier}' in namespace '${namespace}' was disclosed through deviceSigned, but the device key is not authorized for it in the mobile security object`,\n },\n unauthorized,\n disallowed\n )\n continue\n }\n\n if (disallowed) {\n failure(\n claim,\n {\n failure: 'disallowedSource',\n disclosedFrom: disallowed.source,\n reason: `Element '${disallowed.elementIdentifier}' in namespace '${namespace}' was disclosed through ${disallowed.source}, but must be disclosed through ${source}`,\n },\n disallowed\n )\n continue\n }\n\n failure(claim, {\n failure: 'notDisclosed',\n reason: `Element '${elementIdentifier}' in namespace '${namespace}' was not disclosed`,\n })\n }\n }\n\n return {\n claims,\n unusedElements: available\n .filter((element) => !usedElements.has(element))\n .map(({ issuerSignedItem: _, ...element }) => element),\n }\n}\n\nconst toClaimsMatchResult = (claims: Array<ElementMatch>): ClaimsMatchResult => {\n const validClaims = claims.flatMap(({ claim }) => (claim.success ? [claim] : []))\n const failedClaims = claims.flatMap(({ claim }) => (claim.success ? [] : [claim]))\n\n if (isNonEmptyArray(failedClaims) && failedClaims.some((claim) => !claim.optional)) {\n return { success: false, validClaims, failedClaims }\n }\n\n // Every failed claim is optional, and optional elements never make the claims fail.\n return { success: true, validClaims, failedClaims: failedClaims.filter(isOptionalClaim) }\n}\n\nconst isOptionalClaim = (claim: ClaimMatchFailure): claim is ClaimMatchFailure & { optional: true } => claim.optional\n\n/**\n * The match options per doc request index, after checking that every option refers to a doc request\n * of the device request, and that no doc request has options more than once.\n */\nconst indexDocRequestOptions = (deviceRequest: DeviceRequest, matchOptions?: DeviceRequestMatchOptions) => {\n const docRequestOptions = new Map<number, DocRequestMatchOptions>()\n\n for (const options of matchOptions?.docRequests ?? []) {\n const { docRequestIndex } = options\n if (\n !Number.isInteger(docRequestIndex) ||\n docRequestIndex < 0 ||\n docRequestIndex >= deviceRequest.docRequests.length\n ) {\n throw new InvalidDeviceRequestMatchOptionsError(\n `Match options refer to doc request ${docRequestIndex}, but the device request has ${deviceRequest.docRequests.length} doc request(s)`\n )\n }\n if (docRequestOptions.has(docRequestIndex)) {\n throw new InvalidDeviceRequestMatchOptionsError(\n `Match options are provided more than once for doc request ${docRequestIndex}`\n )\n }\n docRequestOptions.set(docRequestIndex, options)\n }\n\n return docRequestOptions\n}\n\n/**\n * Throw an `InvalidDeviceRequestMatchOptionsError` when the match options do not fit the device\n * request, so that verification can fail on them before it does any work.\n *\n * @internal\n */\nexport const validateDeviceRequestMatchOptions = (\n deviceRequest: DeviceRequest,\n matchOptions?: DeviceRequestMatchOptions\n) => {\n indexDocRequestOptions(deviceRequest, matchOptions)\n}\n\nconst isNonEmptyArray = <T>(array: Array<T>): array is NonEmptyArray<T> => array.length > 0\n\n/**\n * The element that answers a request for `elementIdentifier`, either by identifier or, for an age\n * attestation, by the substitution 18013-5 7.2.5 allows.\n *\n * @internal\n */\nexport const findElement = <Candidate extends { elementIdentifier: DataElementIdentifier; elementValue: unknown }>(\n elementIdentifier: DataElementIdentifier,\n candidates: Array<Candidate>\n) =>\n candidates.find((candidate) => candidate.elementIdentifier === elementIdentifier) ??\n findAgeOverCandidate(elementIdentifier, candidates)\n\nconst collectElements = (issuerSigned: IssuerSigned, deviceNamespaces?: DeviceNamespaces) => {\n const elements: Array<ElementCandidate> = []\n\n for (const [namespace, issuerSignedItems] of issuerSigned.issuerNamespaces?.issuerNamespaces ?? []) {\n for (const issuerSignedItem of issuerSignedItems) {\n elements.push({\n namespace,\n elementIdentifier: issuerSignedItem.elementIdentifier,\n elementValue: issuerSignedItem.elementValue,\n source: 'issuerSigned',\n issuerSignedItem,\n })\n }\n }\n\n for (const [namespace, deviceSignedItems] of deviceNamespaces?.deviceNamespaces ?? []) {\n for (const [elementIdentifier, elementValue] of deviceSignedItems.deviceSignedItems) {\n elements.push({ namespace, elementIdentifier, elementValue, source: 'deviceSigned' })\n }\n }\n\n return elements\n}\n\n/**\n * Report a {@link DeviceRequestMatchResult} through a verification callback.\n *\n * A doc request that is not satisfied is a `FAILED` check; over-disclosure and documents that were\n * never requested are reported as `WARNING`, as they are the mdoc's doing and it is up to the\n * verifier whether to accept the response anyway. When the doc requests are matched as alternatives,\n * a single check is reported instead, which only fails when none of them is satisfied.\n *\n * The match is attached to the doc request checks as their structured `result`, so that it survives\n * a callback that throws on a `FAILED` check instead of collecting them.\n */\nexport const reportDeviceRequestMatch = (match: DeviceRequestMatchResult, onCheck: VerificationCallback) => {\n const result = { type: 'deviceRequestMatch', match } as const\n\n if (match.docRequestsAsAlternatives) {\n const check = `Device response must satisfy at least one of the alternative doc requests ${match.docRequests\n .map((docRequest) => `${docRequest.docRequestIndex} for docType '${docRequest.docType}'`)\n .join(', ')}`\n\n if (match.success) {\n onCheck({ status: 'PASSED', check, category: 'DOCUMENT_FORMAT', result })\n } else {\n onCheck({\n status: 'FAILED',\n check,\n category: 'DOCUMENT_FORMAT',\n reason: match.docRequests\n .map((docRequest) => `Doc request ${docRequest.docRequestIndex}: ${docRequestFailureReason(docRequest)}`)\n .join('. '),\n result,\n })\n }\n } else {\n for (const docRequest of match.docRequests) {\n const check = `Device response must satisfy doc request ${docRequest.docRequestIndex} for docType '${docRequest.docType}'`\n\n if (docRequest.success) {\n onCheck({ status: 'PASSED', check, category: 'DOCUMENT_FORMAT', result })\n } else {\n onCheck({\n status: 'FAILED',\n check,\n category: 'DOCUMENT_FORMAT',\n reason: docRequestFailureReason(docRequest),\n result,\n })\n }\n }\n }\n\n for (const { documentIndex, docRequestIndexes, unrequestedClaims } of findOverDisclosure(match)) {\n const docRequests =\n docRequestIndexes.length === 1\n ? `doc request ${docRequestIndexes[0]}`\n : `doc requests ${docRequestIndexes.join(', ')}`\n\n onCheck({\n status: 'WARNING',\n check: `Document ${documentIndex} must not disclose elements that were not requested`,\n category: 'DOCUMENT_FORMAT',\n reason: `Document ${documentIndex} disclosed ${unrequestedClaims\n .map((claim) => `'${claim.elementIdentifier}' in namespace '${claim.namespace}'`)\n .join(', ')}, which ${docRequests} did not ask for`,\n })\n }\n\n if (match.unrequestedDocuments.length > 0) {\n onCheck({\n status: 'WARNING',\n check: 'Device response must not contain documents that were not requested',\n category: 'DOCUMENT_FORMAT',\n reason: `Device response contains ${match.unrequestedDocuments\n .map((document) => `document ${document.documentIndex} with docType '${document.docType}'`)\n .join(', ')}, which the device request did not ask for`,\n })\n }\n}\n\n/**\n * Per document, the elements it disclosed that no doc request it may answer asked for, in response\n * order. The response does not say which doc request a document answers, so every doc request of\n * its docType is considered, also one the document fails: with two doc requests of the same\n * docType, an element is only over-disclosed when neither asks for it. A document of another docType\n * does not answer the doc request, and is reported as an unrequested document instead.\n */\nconst findOverDisclosure = (match: DeviceRequestMatchResult) => {\n const documents = new Map<number, { docRequestIndexes: Array<number>; unrequestedClaims: Array<DisclosedElement> }>()\n\n for (const docRequest of match.docRequests) {\n for (const document of [...docRequest.validDocuments, ...docRequest.failedDocuments]) {\n if (!document.docType.success) continue\n\n const { unrequestedClaims } = document.claims\n const overDisclosure = documents.get(document.documentIndex)\n if (!overDisclosure) {\n documents.set(document.documentIndex, { docRequestIndexes: [docRequest.docRequestIndex], unrequestedClaims })\n continue\n }\n\n overDisclosure.docRequestIndexes.push(docRequest.docRequestIndex)\n overDisclosure.unrequestedClaims = overDisclosure.unrequestedClaims.filter((claim) =>\n unrequestedClaims.some(\n (other) =>\n other.namespace === claim.namespace &&\n other.elementIdentifier === claim.elementIdentifier &&\n other.source === claim.source\n )\n )\n }\n }\n\n return Array.from(documents, ([documentIndex, overDisclosure]) => ({ documentIndex, ...overDisclosure }))\n .filter(({ unrequestedClaims }) => unrequestedClaims.length > 0)\n .sort((a, b) => a.documentIndex - b.documentIndex)\n}\n\nconst docRequestFailureReason = (docRequest: DocRequestMatch) => {\n // Documents of another docType are not an attempt to answer this doc request.\n const documents = docRequest.failedDocuments.filter(\n (document) => document.docType.success || document.docType.docType === docRequest.docType\n )\n\n if (documents.length === 0) {\n return `Device response does not contain a document with docType '${docRequest.docType}'`\n }\n\n return documents\n .map((document) => {\n if (!document.docType.success) return `Document ${document.documentIndex}: ${document.docType.reason}`\n\n const failedClaims = document.claims.failedClaims.filter((claim) => !claim.optional)\n return `Document ${document.documentIndex}: ${failedClaims.map((claim) => claim.reason).join('; ')}`\n })\n .join('. ')\n}\n","import { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { DeviceAuth, type DeviceAuthEncodedStructure } from './device-auth'\nimport { DeviceNamespaces } 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 map.set('nameSpaces', DeviceNamespaces.fromDataItem(input.get('nameSpaces')))\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 // `DeviceNameSpacesBytes` are embedded as received, as device authentication covers them.\n map.set('nameSpaces', output.get('nameSpaces').asDataItem)\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\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 get errorItems() {\n return this.structure\n }\n\n public getErrorCode(dataElementIdentifier: DataElementIdentifier) {\n return this.structure.get(dataElementIdentifier)\n }\n\n public static create(options: ErrorItemsOptions) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(options.errorItems)\n }\n}\n","import { CborStructure } from '@owf/cose'\nimport z from 'zod'\nimport { ErrorItems, errorItemsSchema } from './error-items'\nimport type { Namespace } from './namespace'\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 /**\n * Map where keys are namespaces and values are the errored data elements within that namespace\n */\n public get errors() {\n return this.structure\n }\n\n public getErrorItems(namespace: Namespace) {\n return this.structure.get(namespace)\n }\n\n public static create(options: ErrorsOptions) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(options.errors)\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 { Errors, type ErrorsEncodedStructure } from './errors'\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.instanceof(Errors).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?: Errors\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', Errors.fromEncodedStructure(input.get('errors') as ErrorsEncodedStructure))\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 const errors = output.get('errors')\n if (errors) {\n map.set('errors', errors.encodedStructure)\n }\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import { CborStructure } from '@owf/cose'\nimport { z } from 'zod'\n\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 MacAlgorithm,\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 { describeAgeOverLimitViolations, findAgeOverLimitViolations } from '../../utils/ageOver'\nimport { getOwnProperty } from '../../utils/getOwnProperty'\nimport {\n describeUnauthorizedDeviceSignedElements,\n findUnauthorizedDeviceSignedElements,\n} from '../../utils/keyAuthorizations'\nimport {\n type ClaimMatch,\n type DeviceRequestMatchOptions,\n type DeviceRequestMatchResult,\n matchDeviceRequest,\n matchElements,\n reportDeviceRequestMatch,\n validateDeviceRequestMatchOptions,\n} from '../../utils/matchDeviceRequest'\nimport { verifyVersion } from '../../utils/version'\nimport { defaultVerificationCallback, type VerificationCallback } from '../check-callback'\nimport {\n AgeOverLimitExceededError,\n DeviceKeyNotAuthorizedError,\n DocTypeMismatchError,\n EitherSignatureOrMacMustBeProvidedError,\n InvalidElementSelectionError,\n MissingRequestedElementError,\n} from '../errors'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport type { DataElementValue } from './data-element-value'\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 { DeviceSignedItems } from './device-signed-items'\nimport type { DocRequest } from './doc-request'\nimport { Document, type DocumentEncodedStructure } from './document'\nimport { DocumentError, type DocumentErrorStructure } from './document-error'\nimport type { IssuerAuthVerificationResult } from './issuer-auth'\nimport { IssuerNamespaces } from './issuer-namespaces'\nimport { IssuerSigned } from './issuer-signed'\nimport type { IssuerSignedItem } from './issuer-signed-item'\nimport type { KeyAuthorizations } from './key-authorizations'\nimport type { Namespace } from './namespace'\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 DocumentVerificationResult = IssuerAuthVerificationResult & { document: Document }\n\nexport type DeviceResponseVerificationResult = {\n /**\n * One entry per document in the device response, in response order.\n */\n documents: Array<DocumentVerificationResult>\n /**\n * How the response matches the device request, per doc request and per requested element. Only\n * present when `deviceRequest` was provided.\n */\n deviceRequestMatch?: DeviceRequestMatchResult\n}\n\n/**\n * A single document to disclose in a device response, authenticated with either a device signature\n * or a device MAC.\n */\nexport type DeviceResponseDocumentOptions = {\n issuerSigned: IssuerSigned\n /**\n * Index into `deviceRequest.docRequests` of the doc request this document answers.\n */\n docRequestIndex: number\n /**\n * The requested elements to disclose, per namespace. Defaults to every element the doc request\n * asks for. Pass a subset to leave out elements, for instance the ones the user declined to share.\n *\n * Two `age_over_NN` requests can be answered with the same age attestation (18013-5 7.2.5), which\n * `disclosedElementIdentifier` of the claims of `Holder.matchDeviceRequest` shows. Such elements\n * have to be selected together or left out together, as leaving out only one would not keep its\n * answer from being disclosed.\n */\n elements?: Record<Namespace, Array<DataElementIdentifier>>\n /**\n * Values to disclose device-signed. Every selected requested element that is not issuer-signed,\n * but that the device key is authorized for in the MSO, has to be provided here. Only the values\n * of selected requested elements are disclosed and authenticated, so a value that is not requested\n * or that `elements` leaves out is not.\n */\n deviceNamespaces?: DeviceNamespaces\n signature?: {\n signingKey: CoseKey\n }\n mac?: {\n ephemeralKey: CoseKey\n signingKey: CoseKey\n }\n}\n\nexport class DeviceResponse extends CborStructure<DeviceResponseEncodedStructure, DeviceResponseDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(deviceResponseEncodedSchema.in, deviceResponseDecodedSchema.out, {\n decode: (input) => {\n const map = TypedMap.fromMap(input) as DeviceResponseDecodedStructure\n\n if (input.has('documents')) {\n map.set(\n 'documents',\n (input.get('documents') as unknown[]).map((d) =>\n Document.fromEncodedStructure(d as DocumentEncodedStructure)\n )\n )\n }\n\n if (input.has('documentErrors')) {\n map.set(\n 'documentErrors',\n (input.get('documentErrors') as unknown[]).map((d) =>\n DocumentError.fromEncodedStructure(d as DocumentErrorStructure)\n )\n )\n }\n\n return map\n },\n encode: (output) => {\n const map: Map<unknown, unknown> = output.toMap()\n\n const documents = output.get('documents')\n if (documents !== undefined) {\n map.set(\n 'documents',\n documents.map((d) => d.encodedStructure)\n )\n }\n\n const documentErrors = output.get('documentErrors')\n if (documentErrors !== undefined) {\n map.set(\n 'documentErrors',\n documentErrors.map((d) => d.encodedStructure)\n )\n }\n\n return map\n },\n })\n }\n\n public get version() {\n return this.structure.get('version')\n }\n\n public get documents() {\n return this.structure.get('documents')\n }\n\n public get documentErrors() {\n return this.structure.get('documentErrors')\n }\n\n public get status() {\n return this.structure.get('status')\n }\n\n public async verify(\n options: {\n deviceRequest?: DeviceRequest\n deviceRequestMatchOptions?: DeviceRequestMatchOptions\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 // Invalid match options are a mistake of the caller, so fail on them before verifying anything.\n if (options.deviceRequest) {\n validateDeviceRequestMatchOptions(options.deviceRequest, options.deviceRequestMatchOptions)\n }\n\n verifyVersion({ structure: 'Device Response', version: this.structure.get('version') }, onCheck)\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 // 18013-5 8.3.2.1.2.3 Table 8: an mdoc returning a status other than 0 must not return documents.\n const status = this.structure.get('status')\n onCheck({\n status: status === 0 || !documents?.length ? 'PASSED' : 'FAILED',\n check: 'Device Response must not include documents when the status is not 0.',\n category: 'DOCUMENT_FORMAT',\n reason:\n status !== 0 && documents?.length\n ? `Device Response has status ${status} but returned ${documents.length} document(s)`\n : undefined,\n })\n\n const documentResults: Array<DocumentVerificationResult> = []\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\n // 18013-5 9.3.1 step 4: the docType of the document is not signed, so it must be the docType of\n // the MSO, whether or not a device request is matched.\n const mobileSecurityObjectDocType = document.issuerSigned.issuerAuth.mobileSecurityObject.docType\n onCheck({\n status: document.docType === mobileSecurityObjectDocType ? 'PASSED' : 'FAILED',\n check: 'The docType of the document must match the docType of the mobile security object.',\n category: 'ISSUER_AUTH',\n reason:\n document.docType !== mobileSecurityObjectDocType\n ? `Document has docType '${document.docType}', but the mobile security object has docType '${mobileSecurityObjectDocType}'`\n : undefined,\n })\n\n documentResults.push({\n trustedIssuanceChain,\n statusList,\n trustedStatusListChain,\n identifierList,\n trustedIdentifierListChain,\n document,\n })\n }\n\n let deviceRequestMatch: DeviceRequestMatchResult | undefined\n if (options.deviceRequest) {\n deviceRequestMatch = matchDeviceRequest({\n deviceRequest: options.deviceRequest,\n deviceResponse: this,\n matchOptions: options.deviceRequestMatchOptions,\n })\n reportDeviceRequestMatch(deviceRequestMatch, onCheck)\n }\n\n return { documents: documentResults, deviceRequestMatch }\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 /**\n * Create a single disclosed `Document` for one `DocRequest`, authenticated with either a\n * device signature or a device MAC.\n */\n private static async createDocument(\n options: {\n docRequest: DocRequest\n docRequestIndex: number\n sessionTranscript: SessionTranscript | Uint8Array\n issuerSigned: IssuerSigned\n elements?: Record<Namespace, Array<DataElementIdentifier>>\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 { docRequest } = options\n const docType = docRequest.itemsRequest.docType\n\n // Every access to the mobile security object decodes it, so decode it once.\n const mobileSecurityObject = options.issuerSigned.issuerAuth.mobileSecurityObject\n const { keyAuthorizations } = mobileSecurityObject.deviceKeyInfo\n\n // The document is labeled with the requested docType, which is not signed, so a credential of\n // another docType would produce a document every reader has to reject.\n if (mobileSecurityObject.docType !== docType) {\n throw new DocTypeMismatchError(\n `Credential has docType '${mobileSecurityObject.docType}', but doc request ${options.docRequestIndex} requests docType '${docType}'`\n )\n }\n\n // Only the selected elements are disclosed, so values in `deviceNamespaces` that are not requested\n // do not need to be authorized, the same as `Holder.matchDeviceRequest` ignores them.\n const { issuerNamespaces: disclosedIssuerNamespaces, deviceNamespaces } = DeviceResponse.selectElements({\n docRequest,\n issuerSigned: options.issuerSigned,\n keyAuthorizations,\n deviceNamespaces: options.deviceNamespaces,\n elements: options.elements,\n })\n\n // 18013-5 9.1.3.4 binds the mdoc as well as the mdoc reader. Selection only picks authorized\n // device-signed elements, so this guards that invariant rather than emit a response every reader\n // must reject.\n const unauthorized = findUnauthorizedDeviceSignedElements({ deviceNamespaces, keyAuthorizations })\n if (unauthorized.length > 0) {\n throw new DeviceKeyNotAuthorizedError(describeUnauthorizedDeviceSignedElements(unauthorized))\n }\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 deviceAuthOptions: DeviceAuthOptions = {}\n if (useSignature) {\n const deviceSignature = await DeviceSignature.create({\n unprotectedHeaders,\n protectedHeaders: ProtectedHeaders.create({\n protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.Algorithm, signingKey.algorithm]]),\n }),\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 // 18013-5 9.1.3.5: the device MAC is always HMAC 256/256, keyed with the EMacKey derived from\n // the device key, and not with the algorithm of the device key.\n const deviceMac = DeviceMac.create({\n protectedHeaders: ProtectedHeaders.create({\n protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.Algorithm, MacAlgorithm.HS256]]),\n }),\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(\n { key: macKey, algorithm: MacAlgorithm.HS256, detachedPayload: deviceAuthenticationBytes },\n ctx.cose.mac0\n )\n\n deviceAuthOptions.deviceMac = deviceMac\n }\n\n return Document.create({\n docType,\n issuerSigned: IssuerSigned.create({\n issuerNamespaces: disclosedIssuerNamespaces,\n issuerAuth: options.issuerSigned.issuerAuth,\n }),\n deviceSigned: DeviceSigned.create({\n deviceNamespaces,\n deviceAuth: DeviceAuth.create(deviceAuthOptions),\n }),\n })\n }\n\n /**\n * The issuer-signed items and device-signed elements to disclose for a doc request, selected the\n * same way as `Holder.matchDeviceRequest` matches a credential: a requested element is disclosed\n * issuer-signed when the issuer signed it, and otherwise device-signed when the device key is\n * authorized for it and its value is in the device namespaces.\n *\n * Only the selected requested elements are disclosed, from either source: a device-signed element\n * that is not requested, or that `elements` leaves out, is not disclosed.\n */\n private static selectElements(options: {\n docRequest: DocRequest\n issuerSigned: IssuerSigned\n keyAuthorizations: KeyAuthorizations | undefined\n deviceNamespaces?: DeviceNamespaces\n elements?: Record<Namespace, Array<DataElementIdentifier>>\n }) {\n const { claims } = matchElements({\n mode: 'holder',\n namespaces: options.docRequest.itemsRequest.namespaces,\n issuerSigned: options.issuerSigned,\n keyAuthorizations: options.keyAuthorizations,\n deviceNamespaces: options.deviceNamespaces,\n })\n\n if (options.elements) {\n for (const [namespace, elementIdentifiers] of Object.entries(options.elements)) {\n for (const elementIdentifier of elementIdentifiers) {\n if (!options.docRequest.itemsRequest.namespaces.get(namespace)?.has(elementIdentifier)) {\n throw new InvalidElementSelectionError(\n `Element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but the doc request does not request it`\n )\n }\n }\n }\n }\n\n const isSelected = ({ namespace, elementIdentifier }: ClaimMatch) =>\n options.elements ? (getOwnProperty(options.elements, namespace)?.includes(elementIdentifier) ?? false) : true\n\n // The element that answers each requested element left out of the selection, with that claim.\n const declinedElements = new Map(\n claims.flatMap(({ claim, element }) => (element && !isSelected(claim) ? [[element, claim] as const] : []))\n )\n\n const issuerNamespaces = new Map<Namespace, Array<IssuerSignedItem>>()\n const deviceNamespaces = new Map<Namespace, Map<DataElementIdentifier, DataElementValue>>()\n for (const match of claims) {\n const { claim } = match\n if (!isSelected(claim)) continue\n\n if (match.element === undefined) throw new MissingRequestedElementError(match.claim.reason)\n const { element } = match\n\n // An age attestation can answer more than one `age_over_NN` request (18013-5 7.2.5).\n // Disclosing it for this element would also answer a requested element that is left out, so\n // leaving that one out would have no effect.\n const declined = declinedElements.get(element)\n if (declined) {\n throw new InvalidElementSelectionError(\n `Element '${claim.elementIdentifier}' in namespace '${claim.namespace}' is selected for disclosure, but it is answered with '${element.elementIdentifier}', which also answers '${declined.elementIdentifier}' that is not selected. Select both or neither`\n )\n }\n\n if (!element.issuerSignedItem) {\n const items = deviceNamespaces.get(element.namespace) ?? new Map()\n items.set(element.elementIdentifier, element.elementValue)\n deviceNamespaces.set(element.namespace, items)\n continue\n }\n\n const items = issuerNamespaces.get(claim.namespace) ?? []\n // An age attestation can answer more than one `age_over_NN` request, but is disclosed once.\n if (!items.includes(element.issuerSignedItem)) items.push(element.issuerSignedItem)\n issuerNamespaces.set(claim.namespace, items)\n }\n\n // 18013-5 7.2.5: a reader must not request more than two age attestations, as together they\n // narrow down the age of the holder. Only what is disclosed counts, so a holder can still answer\n // such a request by selecting at most two of them.\n const disclosedElementIdentifiers = new Map<Namespace, Array<DataElementIdentifier>>(\n Array.from(issuerNamespaces, ([namespace, items]) => [namespace, items.map((item) => item.elementIdentifier)])\n )\n for (const [namespace, items] of deviceNamespaces) {\n disclosedElementIdentifiers.set(namespace, [\n ...(disclosedElementIdentifiers.get(namespace) ?? []),\n ...items.keys(),\n ])\n }\n const ageOverLimitViolations = findAgeOverLimitViolations(disclosedElementIdentifiers)\n if (ageOverLimitViolations.length > 0) {\n throw new AgeOverLimitExceededError(\n `Doc request would be answered with ${describeAgeOverLimitViolations(ageOverLimitViolations)}, but at most two age_over_NN elements may be disclosed per namespace. Select at most two of them`\n )\n }\n\n return {\n // `IssuerNameSpaces` must have at least one namespace, so it is left out when no issuer-signed\n // element is disclosed.\n issuerNamespaces: issuerNamespaces.size > 0 ? IssuerNamespaces.create({ issuerNamespaces }) : undefined,\n deviceNamespaces: DeviceNamespaces.create({\n deviceNamespaces: new Map(\n Array.from(deviceNamespaces, ([namespace, items]) => [\n namespace,\n DeviceSignedItems.create({ deviceSignedItems: items }),\n ])\n ),\n }),\n }\n }\n\n private static fromDocuments(documents: Array<Document>) {\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 private static findDocRequest(deviceRequest: DeviceRequest, docRequestIndex: number): DocRequest {\n const docRequest = deviceRequest.docRequests[docRequestIndex]\n if (!docRequest) throw new Error(`No doc request found at index ${docRequestIndex}`)\n\n return docRequest\n }\n\n /**\n * Create a device response for a device request.\n *\n * Every document brings its own device key and, optionally, its own device namespaces, and names\n * the doc request it answers through `docRequestIndex`, so a request may also be answered\n * partially.\n */\n public static async createWithDeviceRequest(\n options: {\n deviceRequest: DeviceRequest\n sessionTranscript: SessionTranscript | Uint8Array\n documents: Array<DeviceResponseDocumentOptions>\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose'>\n ) {\n const documents = await Promise.all(\n options.documents.map((document) =>\n DeviceResponse.createDocument(\n {\n docRequest: DeviceResponse.findDocRequest(options.deviceRequest, document.docRequestIndex),\n docRequestIndex: document.docRequestIndex,\n sessionTranscript: options.sessionTranscript,\n issuerSigned: document.issuerSigned,\n elements: document.elements,\n deviceNamespaces: document.deviceNamespaces,\n signature: document.signature,\n mac: document.mac,\n },\n ctx\n )\n )\n )\n\n return DeviceResponse.fromDocuments(documents)\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 // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import { CborStructure, TypedMap, typedMap, zUint8Array } from '@owf/cose'\nimport type { z } from 'zod'\n\nconst encryptedResponseDataSchema = typedMap([\n ['enc', zUint8Array],\n ['cipherText', zUint8Array],\n] as const)\n\nexport type EncryptedResponseDataDecodedStructure = z.output<typeof encryptedResponseDataSchema>\nexport type EncryptedResponseDataEncodedStructure = z.input<typeof encryptedResponseDataSchema>\n\nexport type EncryptedResponseDataOptions = {\n /**\n * Raw serialized HPKE encapsulated key. For DHKEM(P-256) this is the 65-byte\n * uncompressed SEC1 point, not a COSE_Key.\n */\n enc: Uint8Array\n ciphertext: Uint8Array\n}\n\n/**\n * EncryptedResponseData as defined in ISO/IEC TS 18013-7:2025 C.3.\n *\n * EncryptedResponseData = { \"enc\": bstr, \"cipherText\": bstr }\n */\nexport class EncryptedResponseData extends CborStructure<\n EncryptedResponseDataEncodedStructure,\n EncryptedResponseDataDecodedStructure\n> {\n public static override get encodingSchema() {\n return encryptedResponseDataSchema\n }\n\n public get enc() {\n return this.structure.get('enc')\n }\n\n public get ciphertext() {\n return this.structure.get('cipherText')\n }\n\n public static create(options: EncryptedResponseDataOptions): EncryptedResponseData {\n const map: EncryptedResponseDataDecodedStructure = new TypedMap([\n ['enc', options.enc],\n ['cipherText', options.ciphertext],\n ])\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import { CborStructure } from '@owf/cose'\nimport { base64url } from '@owf/identity-common'\nimport { z } from 'zod'\nimport { EncryptedResponseData, type EncryptedResponseDataEncodedStructure } from './encrypted-response-data'\n\nconst encryptedResponseEncodedSchema = z.tuple([z.literal('dcapi'), z.map(z.unknown(), z.unknown())])\nconst encryptedResponseDecodedSchema = z.instanceof(EncryptedResponseData)\n\nexport type EncryptedResponseEncodedStructure = z.infer<typeof encryptedResponseEncodedSchema>\nexport type EncryptedResponseDecodedStructure = z.infer<typeof encryptedResponseDecodedSchema>\n\nexport type EncryptedResponseOptions = {\n encryptedResponseData: EncryptedResponseData\n}\n\n/**\n * EncryptedResponse as defined in ISO/IEC TS 18013-7:2025 C.3.\n *\n * EncryptedResponse = [ \"dcapi\", EncryptedResponseData ]\n */\nexport class EncryptedResponse extends CborStructure<\n EncryptedResponseEncodedStructure,\n EncryptedResponseDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(encryptedResponseEncodedSchema, encryptedResponseDecodedSchema, {\n decode: ([, encryptedResponseData]) =>\n EncryptedResponseData.fromEncodedStructure(encryptedResponseData as EncryptedResponseDataEncodedStructure),\n encode: (encryptedResponseData) =>\n ['dcapi', encryptedResponseData.encodedStructure] satisfies EncryptedResponseEncodedStructure,\n })\n }\n\n public get encryptedResponseData() {\n return this.structure\n }\n\n public get enc() {\n return this.structure.enc\n }\n\n public get ciphertext() {\n return this.structure.ciphertext\n }\n\n public static create(options: EncryptedResponseOptions): EncryptedResponse {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(options.encryptedResponseData)\n }\n\n public static fromBase64Url(encryptedResponse: string): EncryptedResponse {\n // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\n return this.decode(base64url.decode(encryptedResponse))\n }\n\n public toBase64Url(): string {\n return base64url.encode(this.encode())\n }\n}\n","import { CborStructure, CoseKey, type CoseKeyEncodedStructure, TypedMap, typedMap, zUint8Array } from '@owf/cose'\nimport { z } from 'zod'\n\nconst encryptionParametersSchema = typedMap([\n ['nonce', zUint8Array],\n ['recipientPublicKey', z.instanceof(CoseKey)],\n] as const)\n\nexport type EncryptionParametersDecodedStructure = z.output<typeof encryptionParametersSchema>\nexport type EncryptionParametersEncodedStructure = z.input<typeof encryptionParametersSchema>\n\nexport type EncryptionParametersOptions = {\n nonce: Uint8Array\n recipientPublicKey: CoseKey\n}\n\n/**\n * EncryptionParameters as defined in ISO/IEC TS 18013-7:2025 C.2.\n *\n * EncryptionParameters = { \"nonce\": bstr, \"recipientPublicKey\": COSE_Key }\n */\nexport class EncryptionParameters extends CborStructure<\n EncryptionParametersEncodedStructure,\n EncryptionParametersDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(encryptionParametersSchema.in, encryptionParametersSchema.out, {\n decode: (input) => {\n const map = TypedMap.fromMap(input) as EncryptionParametersDecodedStructure\n\n map.set(\n 'recipientPublicKey',\n CoseKey.fromEncodedStructure(input.get('recipientPublicKey') as CoseKeyEncodedStructure)\n )\n\n return map\n },\n encode: (output) => {\n const map = output.toMap() as Map<unknown, unknown>\n map.set('recipientPublicKey', output.get('recipientPublicKey').encodedStructure)\n\n return map\n },\n })\n }\n\n public get nonce() {\n return this.structure.get('nonce')\n }\n\n public get recipientPublicKey() {\n return this.structure.get('recipientPublicKey')\n }\n\n public static create(options: EncryptionParametersOptions): EncryptionParameters {\n const map: EncryptionParametersDecodedStructure = new TypedMap([\n ['nonce', options.nonce],\n ['recipientPublicKey', options.recipientPublicKey],\n ])\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n}\n","import { CborStructure } from '@owf/cose'\nimport { base64url } from '@owf/identity-common'\nimport { z } from 'zod'\nimport { EncryptionParameters, type EncryptionParametersEncodedStructure } from './encryption-parameters'\n\nconst encryptionInfoEncodedSchema = z.tuple([z.literal('dcapi'), z.map(z.unknown(), z.unknown())])\nconst encryptionInfoDecodedSchema = z.instanceof(EncryptionParameters)\n\nexport type EncryptionInfoEncodedStructure = z.infer<typeof encryptionInfoEncodedSchema>\nexport type EncryptionInfoDecodedStructure = z.infer<typeof encryptionInfoDecodedSchema>\n\nexport type EncryptionInfoOptions = {\n encryptionParameters: EncryptionParameters\n}\n\n/**\n * EncryptionInfo as defined in ISO/IEC TS 18013-7:2025 C.2.\n *\n * EncryptionInfo = [ \"dcapi\", EncryptionParameters ]\n */\nexport class EncryptionInfo extends CborStructure<EncryptionInfoEncodedStructure, EncryptionInfoDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(encryptionInfoEncodedSchema, encryptionInfoDecodedSchema, {\n decode: ([, encryptionParameters]) =>\n EncryptionParameters.fromEncodedStructure(encryptionParameters as EncryptionParametersEncodedStructure),\n encode: (encryptionParameters) =>\n ['dcapi', encryptionParameters.encodedStructure] satisfies EncryptionInfoEncodedStructure,\n })\n }\n\n public get encryptionParameters() {\n return this.structure\n }\n\n public get nonce() {\n return this.structure.nonce\n }\n\n public get recipientPublicKey() {\n return this.structure.recipientPublicKey\n }\n\n public static create(options: EncryptionInfoOptions): EncryptionInfo {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(options.encryptionParameters)\n }\n\n public static fromBase64Url(encryptionInfo: string): EncryptionInfo {\n // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\n return this.decode(base64url.decode(encryptionInfo))\n }\n\n public toBase64Url(): string {\n return base64url.encode(this.encode())\n }\n}\n","import {\n type CoseKey,\n 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 { UnsupportedDeviceMacAlgorithmError } from '../errors'\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 if (!this.namespaces.getDeviceNamespace(namespace)) {\n this.namespaces.setDeviceNamespace(namespace, DeviceSignedItems.create({ deviceSignedItems: new Map() }))\n }\n\n for (const [elementIdentifier, elementValue] of Object.entries(value)) {\n this.namespaces.setDeviceSignedElement(namespace, elementIdentifier, elementValue)\n }\n\n return this\n }\n\n public async sign(options: {\n signingKey: CoseKey\n algorithm: SignatureAlgorithm\n sessionTranscript: SessionTranscript\n }): Promise<DeviceSigned> {\n const protectedHeaders = ProtectedHeaders.create({\n protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.Algorithm, options.algorithm]]),\n })\n\n const unprotectedHeaders = UnprotectedHeaders.create({})\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 }): Promise<DeviceSigned> {\n // 18013-5 9.1.3.5: the device MAC shall use HMAC 256/256, which `DeviceAuth.verify` enforces.\n if (options.algorithm !== MacAlgorithm.HS256) {\n throw new UnsupportedDeviceMacAlgorithmError(\n `Device MAC algorithm must be HMAC 256/256 (${MacAlgorithm.HS256}), received ${options.algorithm}`\n )\n }\n\n const protectedHeaders = ProtectedHeaders.create({\n protectedHeaders: new Map<number, unknown>([[RegisteredCwtHeaderClaimKey.Algorithm, options.algorithm]]),\n })\n\n const unprotectedHeaders = UnprotectedHeaders.create({})\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 unprotectedHeaders.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 derivedKey = await deviceMac.createDeviceMacKey(\n {\n privateKey: options.privateKey,\n publicKey: options.publicKey,\n sessionTranscript: options.sessionTranscript,\n info: 'EMacKey',\n },\n this.ctx\n )\n\n const deviceMacWithTag = await deviceMac.authenticate(\n {\n key: derivedKey,\n algorithm: options.algorithm,\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","/**\n * The value of an `x5chain` COSE header (RFC 9360): a single certificate as a byte string, and a\n * chain of more than one certificate as an array, as in the examples of 18013-5 Annex D.\n */\nexport const x5chainHeaderValue = (certificateChain: Array<Uint8Array>): Uint8Array | Array<Uint8Array> =>\n certificateChain.length === 1 ? certificateChain[0] : certificateChain\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 { x5chainHeaderValue } from '../../utils/x5chain'\nimport {\n AtLeastOneCertificateRequiredError,\n DuplicateElementIdentifierError,\n InvalidValidityInfoError,\n MdlError,\n SignatureAlgorithmDoesNotMatchSigningKeyAlgorithmError,\n} 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 // Added to a copy, so that a call that throws leaves the namespace as it was.\n const issuerNamespace = [...(this.namespaces.getIssuerNamespace(namespace) ?? [])]\n\n const entries = values instanceof Map ? Array.from(values.entries()) : Object.entries(values)\n\n for (const [elementIdentifier, elementValue] of entries) {\n if (issuerNamespace.some((item) => item.elementIdentifier === elementIdentifier)) {\n throw new DuplicateElementIdentifierError(\n `Element '${elementIdentifier}' is already added to namespace '${namespace}'`\n )\n }\n\n // Digest IDs identify the digests of a namespace in the MSO, so they must be unique (9.1.2.4)\n const digestId = randomUnsignedInteger(this.ctx)\n if (issuerNamespace.some((item) => item.digestId === digestId)) {\n throw new MdlError(`Generated digest ID ${digestId} is already used in namespace '${namespace}'`)\n }\n\n issuerNamespace.push(\n IssuerSignedItem.fromOptions({\n digestId,\n random: this.ctx.crypto.random(32),\n elementIdentifier,\n elementValue,\n })\n )\n }\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 if (validityInfo.validFrom.getTime() < validityInfo.signed.getTime()) {\n throw new InvalidValidityInfoError(\n `validFrom (${validityInfo.validFrom.toISOString()}) must be equal to or later than signed (${validityInfo.signed.toISOString()})`\n )\n }\n\n if (validityInfo.validUntil.getTime() <= validityInfo.validFrom.getTime()) {\n throw new InvalidValidityInfoError(\n `validUntil (${validityInfo.validUntil.toISOString()}) must be later than validFrom (${validityInfo.validFrom.toISOString()})`\n )\n }\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, x5chainHeaderValue(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 { base64url } from '@owf/identity-common'\nimport type { MdocContext } from './context'\nimport {\n DeviceRequest,\n DeviceResponse,\n type DeviceResponseDocumentOptions,\n defaultVerificationCallback,\n IssuerSigned,\n type IssuerSignedVerificationResult,\n SessionTranscript,\n type VerificationCallback,\n} from './mdoc'\nimport { verifyAgeOverRequestLimit } from './utils/ageOver'\nimport {\n type HolderCredential,\n type HolderDeviceRequestMatchResult,\n matchCredentialsToDeviceRequest,\n} from './utils/matchDeviceRequest'\nimport { verifyVersion } from './utils/version'\n\n// biome-ignore lint/complexity/noStaticOnlyClass: part of the public API\nexport class Holder {\n /**\n * A string `issuerSigned` is base64url encoded, as OpenID4VCI defines it.\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. 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 * Without trust anchors the chain check of a request with reader auth\n * FAILS, unless `disableCertificateChainValidation` is set.\n */\n trustedCertificates?: Array<Uint8Array>\n /**\n * Only verify reader-auth signatures, without establishing trust in the\n * reader's certificate chain.\n */\n disableCertificateChainValidation?: boolean\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 = SessionTranscript.from(options.sessionTranscript)\n\n const onCheck = options.verificationCallback ?? defaultVerificationCallback\n verifyVersion({ structure: 'Device Request', version: deviceRequest.version }, onCheck)\n verifyAgeOverRequestLimit(deviceRequest, onCheck)\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 disableCertificateChainValidation: options.disableCertificateChainValidation,\n now: options.now,\n },\n ctx\n )\n }\n }\n\n /**\n * Match the credentials of the holder against a device request, to select which credentials can\n * answer which doc request. See {@link matchCredentialsToDeviceRequest} for what is matched.\n *\n * `createDeviceResponseForDeviceRequest` selects the elements to disclose the same way, so a\n * credential that matches can answer the doc request with the same `deviceNamespaces`.\n */\n public static matchDeviceRequest(options: {\n deviceRequest: Uint8Array | DeviceRequest\n credentials: Array<IssuerSigned | HolderCredential>\n /**\n * See `DeviceRequestMatchOptions.treatAmbiguousMultipleDocRequestsAsAlternatives`. Defaults to\n * `false`.\n */\n treatAmbiguousMultipleDocRequestsAsAlternatives?: boolean\n }): HolderDeviceRequestMatchResult {\n return matchCredentialsToDeviceRequest({\n deviceRequest:\n options.deviceRequest instanceof DeviceRequest\n ? options.deviceRequest\n : DeviceRequest.decode(options.deviceRequest),\n credentials: options.credentials,\n treatAmbiguousMultipleDocRequestsAsAlternatives: options.treatAmbiguousMultipleDocRequestsAsAlternatives,\n })\n }\n\n public static async createDeviceResponseForDeviceRequest(\n options: {\n deviceRequest: DeviceRequest\n sessionTranscript: SessionTranscript | Uint8Array\n documents: Array<DeviceResponseDocumentOptions>\n },\n context: Pick<MdocContext, 'cose' | 'crypto'>\n ) {\n return await DeviceResponse.createWithDeviceRequest(options, context)\n }\n}\n","import {\n type CoseKey,\n Curve,\n KeyType,\n ProtectedHeaders,\n RegisteredCwtHeaderClaimKey,\n UnprotectedHeaders,\n} from '@owf/cose'\nimport { base64url } from '@owf/identity-common'\nimport { z } from 'zod'\nimport { HpkeSuiteId, type MdocContext } from './context'\nimport {\n DeviceRequest,\n DeviceResponse,\n type DeviceResponseDocumentOptions,\n type DeviceResponseVerificationResult,\n DocRequest,\n defaultVerificationCallback,\n EncryptedResponse,\n EncryptedResponseData,\n EncryptionInfo,\n EncryptionParameters,\n HpkeNotSupportedError,\n InvalidDcApiRequestError,\n InvalidDcApiResponseError,\n InvalidEncryptionInfoError,\n InvalidOriginError,\n ItemsRequest,\n MissingOriginError,\n ReaderAuth,\n ReaderAuthentication,\n SessionTranscript,\n type VerificationCallback,\n} from './mdoc'\nimport { verifyAgeOverRequestLimit } from './utils/ageOver'\nimport type { DeviceRequestMatchOptions } from './utils/matchDeviceRequest'\nimport { verifyVersion } from './utils/version'\nimport { x5chainHeaderValue } from './utils/x5chain'\n\n/**\n * DC API protocol identifier for ISO/IEC TS 18013-7:2025 Annex C.\n */\nexport const isoMdocDcApiProtocol = 'org-iso-mdoc'\n\n/**\n * The only HPKE suite Annex C allows (C.4).\n */\nexport const isoMdocDcApiHpkeSuite = HpkeSuiteId.DhkemP256HkdfSha256HkdfSha256Aes128Gcm\n\n/**\n * Minimum nonce entropy required by C.2.\n */\nconst minimumNonceLength = 16\n\n/**\n * Base64url-no-pad, as Annex C encodes every member of the request and response payloads.\n */\nconst base64UrlSchema = z.base64url().min(1)\n\n/**\n * Request payload exchanged over the DC API (C.2). Both members are base64url-no-pad encoded CBOR.\n */\nexport const isoMdocDcApiRequestSchema = z.object({\n deviceRequest: base64UrlSchema,\n encryptionInfo: base64UrlSchema,\n})\nexport type IsoMdocDcApiRequest = z.infer<typeof isoMdocDcApiRequestSchema>\n\n/**\n * Response payload returned over the DC API (C.3), base64url-no-pad encoded CBOR.\n */\nexport const isoMdocDcApiResponseSchema = z.object({\n response: base64UrlSchema,\n})\nexport type IsoMdocDcApiResponse = z.infer<typeof isoMdocDcApiResponseSchema>\n\n/**\n * The response as it may be handed to {@link IsoMdocDcApi.decryptResponse}, normalized to the\n * base64url `response` string.\n */\nconst isoMdocDcApiResponseInputSchema = z.union([\n base64UrlSchema,\n isoMdocDcApiResponseSchema.transform(({ response }) => response),\n])\n\nexport type IsoMdocDcApiParsedDocRequest = {\n docRequest: DocRequest\n docType: string\n namespaces: Map<string, Map<string, boolean>>\n /**\n * Whether the doc request carries reader auth, which is optional in Annex C. This does not say\n * whether reader auth is valid: an invalid signature or an untrusted certificate chain surfaces\n * through the verification callback.\n */\n hasReaderAuth: boolean\n readerCertificateChain?: Array<Uint8Array>\n}\n\nexport type IsoMdocDcApiParsedRequest = {\n origin: string\n deviceRequest: DeviceRequest\n encryptionInfo: EncryptionInfo\n encryptionInfoBase64Url: string\n sessionTranscript: SessionTranscript\n docRequests: Array<IsoMdocDcApiParsedDocRequest>\n}\n\nexport type IsoMdocDcApiCreatedRequest = {\n request: IsoMdocDcApiRequest\n deviceRequest: DeviceRequest\n encryptionInfo: EncryptionInfo\n sessionTranscript?: SessionTranscript\n}\n\n/**\n * ISO/IEC TS 18013-7:2025 Annex C (`org-iso-mdoc`) request and response handling.\n *\n * The HPKE operations are provided by the caller through `ctx.crypto.hpke`, so this package stays\n * free of a cryptographic backend.\n */\n// biome-ignore lint/complexity/noStaticOnlyClass: part of the public API\nexport class IsoMdocDcApi {\n /**\n * Build an Annex C request (verifier side).\n *\n * When `readerAuth` is provided each doc request is signed over a `ReaderAuthentication`\n * structure that binds the session transcript, and therefore a single `origin` — a signed request\n * can only be used against the origin it was created for.\n */\n public static async createRequest(\n options: {\n docRequests: Array<{\n docType: string\n namespaces: Record<string, Record<string, boolean>> | Map<string, Map<string, boolean>>\n }>\n /**\n * Public key the response is encrypted to. Must be an EC P-256 key.\n */\n recipientPublicKey: CoseKey\n /**\n * At least 16 bytes of entropy, fresh per transaction (C.2). Generated when omitted.\n */\n nonce?: Uint8Array\n version?: string\n readerAuth?: {\n signingKey: CoseKey\n certificateChain: Array<Uint8Array>\n origin: string\n }\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose'>\n ): Promise<IsoMdocDcApiCreatedRequest> {\n const nonce = options.nonce ?? ctx.crypto.random(minimumNonceLength)\n if (nonce.length < minimumNonceLength) {\n throw new InvalidEncryptionInfoError(`Nonce must be at least ${minimumNonceLength} bytes`)\n }\n assertP256PublicKey(options.recipientPublicKey)\n if (options.readerAuth) assertSerializedOrigin(options.readerAuth.origin)\n\n const encryptionInfo = EncryptionInfo.create({\n encryptionParameters: EncryptionParameters.create({ nonce, recipientPublicKey: options.recipientPublicKey }),\n })\n const encryptionInfoBase64Url = encryptionInfo.toBase64Url()\n\n // The transcript only depends on the encryption info and the origin, so it can be computed\n // before the doc requests are signed.\n const sessionTranscript = options.readerAuth\n ? await SessionTranscript.forIsoMdocDcApi({ encryptionInfoBase64Url, origin: options.readerAuth.origin }, ctx)\n : undefined\n\n const docRequests = await Promise.all(\n options.docRequests.map(async ({ docType, namespaces }) => {\n const itemsRequest = ItemsRequest.create({ docType, namespaces })\n\n if (!options.readerAuth || !sessionTranscript) {\n return DocRequest.create({ itemsRequest })\n }\n\n const { signingKey, certificateChain } = options.readerAuth\n const unprotectedHeaders = UnprotectedHeaders.create({})\n unprotectedHeaders.headers?.set(RegisteredCwtHeaderClaimKey.X5Chain, x5chainHeaderValue(certificateChain))\n\n const readerAuth = (await ReaderAuth.create({\n protectedHeaders: ProtectedHeaders.create({\n protectedHeaders: new Map([[RegisteredCwtHeaderClaimKey.Algorithm, signingKey.algorithm]]),\n }),\n unprotectedHeaders,\n payload: null,\n }).sign(\n {\n signingKey,\n detachedPayload: ReaderAuthentication.create({ sessionTranscript, itemsRequest }).encode({\n asDataItem: true,\n }),\n },\n { sign: ctx.cose.sign1.sign }\n )) as ReaderAuth\n\n return DocRequest.create({ itemsRequest, readerAuth })\n })\n )\n\n const deviceRequest = DeviceRequest.create({ version: options.version, docRequests })\n\n return {\n request: {\n deviceRequest: base64url.encode(deviceRequest.encode()),\n encryptionInfo: encryptionInfoBase64Url,\n },\n deviceRequest,\n encryptionInfo,\n sessionTranscript,\n }\n }\n\n /**\n * Parse and validate an Annex C request (wallet side), and verify reader auth where present.\n *\n * `origin` must be the origin the platform provided; C.5 requires the mdoc to abort when no\n * origin was received.\n */\n public static async parseRequest(\n options: {\n request: IsoMdocDcApiRequest\n origin: string | undefined\n /**\n * Trust anchors for reader certificate chains. Without trust anchors the chain check of a doc\n * request with reader auth FAILS, unless `disableReaderCertificateChainValidation` is set.\n */\n trustedReaderCertificates?: Array<Uint8Array>\n /**\n * Only verify reader signatures, without establishing trust in the reader certificate chains.\n */\n disableReaderCertificateChainValidation?: boolean\n verificationCallback?: VerificationCallback\n now?: Date\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose' | 'x509'>\n ): Promise<IsoMdocDcApiParsedRequest> {\n const { origin } = options\n if (!origin) throw new MissingOriginError('No origin was provided by the DC API')\n assertSerializedOrigin(origin)\n\n // The request is handed to us by the platform, so validate its shape before decoding anything.\n const request = parseOrThrow(isoMdocDcApiRequestSchema, options.request, InvalidDcApiRequestError, 'DC API request')\n\n const encryptionInfoBase64Url = request.encryptionInfo\n const encryptionInfo = decodeOrThrow(\n () => EncryptionInfo.fromBase64Url(encryptionInfoBase64Url),\n InvalidDcApiRequestError,\n 'encryption info'\n )\n\n if (encryptionInfo.nonce.length < minimumNonceLength) {\n throw new InvalidEncryptionInfoError(`Nonce must be at least ${minimumNonceLength} bytes`)\n }\n assertP256PublicKey(encryptionInfo.recipientPublicKey)\n\n const deviceRequest = decodeOrThrow(\n () => DeviceRequest.decode(base64url.decode(request.deviceRequest)),\n InvalidDcApiRequestError,\n 'device request'\n )\n const onCheck = options.verificationCallback ?? defaultVerificationCallback\n verifyVersion({ structure: 'Device Request', version: deviceRequest.version }, onCheck)\n verifyAgeOverRequestLimit(deviceRequest, onCheck)\n\n const sessionTranscript = await SessionTranscript.forIsoMdocDcApi({ encryptionInfoBase64Url, origin }, ctx)\n\n const docRequests: Array<IsoMdocDcApiParsedDocRequest> = []\n for (const docRequest of deviceRequest.docRequests) {\n const { readerAuth } = docRequest\n\n if (readerAuth) {\n await readerAuth.verify(\n {\n readerAuthentication: { itemsRequest: docRequest.itemsRequest, sessionTranscript },\n verificationCallback: options.verificationCallback,\n trustedCertificates: options.trustedReaderCertificates,\n disableCertificateChainValidation: options.disableReaderCertificateChainValidation,\n now: options.now,\n },\n ctx\n )\n }\n\n docRequests.push({\n docRequest,\n docType: docRequest.itemsRequest.docType,\n namespaces: docRequest.itemsRequest.namespaces,\n hasReaderAuth: !!readerAuth,\n readerCertificateChain: readerAuth?.certificateChain,\n })\n }\n\n return {\n origin,\n deviceRequest,\n encryptionInfo,\n encryptionInfoBase64Url,\n sessionTranscript,\n docRequests,\n }\n }\n\n /**\n * Create the encrypted Annex C response (wallet side).\n *\n * Device auth uses `deviceSignature`; the MAC variant has no key-agreement channel in the DC API\n * flow.\n */\n public static async createResponse(\n options: {\n parsedRequest: IsoMdocDcApiParsedRequest\n /**\n * The documents to disclose, each naming the doc request of `parsedRequest.docRequests` it\n * answers through `docRequestIndex`. See `DeviceResponse.createWithDeviceRequest` for how the\n * elements to disclose are selected.\n */\n documents: Array<\n Pick<DeviceResponseDocumentOptions, 'issuerSigned' | 'docRequestIndex' | 'elements' | 'deviceNamespaces'> & {\n deviceKey: CoseKey\n }\n >\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose'>\n ): Promise<IsoMdocDcApiResponse> {\n const hpke = assertHpke(ctx)\n const { parsedRequest } = options\n\n const deviceResponse = await DeviceResponse.createWithDeviceRequest(\n {\n deviceRequest: parsedRequest.deviceRequest,\n sessionTranscript: parsedRequest.sessionTranscript,\n documents: options.documents.map((document) => ({\n docRequestIndex: document.docRequestIndex,\n issuerSigned: document.issuerSigned,\n elements: document.elements,\n deviceNamespaces: document.deviceNamespaces,\n signature: { signingKey: document.deviceKey },\n })),\n },\n ctx\n )\n\n const { enc, ciphertext } = await hpke.seal({\n suite: isoMdocDcApiHpkeSuite,\n recipientPublicKey: parsedRequest.encryptionInfo.recipientPublicKey,\n // C.4: `info` is the session transcript encoded as a bare CBOR array, not as\n // SessionTranscriptBytes (tag 24). `aad` is empty.\n info: parsedRequest.sessionTranscript.encode(),\n plaintext: deviceResponse.encode(),\n })\n\n const encryptedResponse = EncryptedResponse.create({\n encryptedResponseData: EncryptedResponseData.create({ enc, ciphertext }),\n })\n\n return { response: encryptedResponse.toBase64Url() }\n }\n\n /**\n * Decrypt an Annex C response (verifier side) without verifying the documents.\n *\n * Decryption is bound to the origin through the session transcript, so a response relayed from a\n * different origin fails here.\n */\n public static async decryptResponse(\n options: {\n response: IsoMdocDcApiResponse | string\n origin: string\n /**\n * The base64url `encryptionInfo` exactly as it was sent to the wallet.\n */\n encryptionInfo: string\n /**\n * The recipient key whose public part was sent to the wallet in `encryptionInfo`. When the\n * private key is held by a key management system, pass the public key carrying the `keyId`\n * the `ctx.crypto.hpke.open` implementation resolves the private key with.\n */\n recipientKey: CoseKey\n },\n ctx: Pick<MdocContext, 'crypto'>\n ): Promise<{ deviceResponse: DeviceResponse; sessionTranscript: SessionTranscript }> {\n const hpke = assertHpke(ctx)\n if (!options.origin) throw new MissingOriginError('No origin was provided by the DC API')\n assertSerializedOrigin(options.origin)\n\n // The response comes from the wallet, so validate its shape before decoding anything.\n const response = parseOrThrow(\n isoMdocDcApiResponseInputSchema,\n options.response,\n InvalidDcApiResponseError,\n 'DC API response'\n )\n\n const encryptedResponse = decodeOrThrow(\n () => EncryptedResponse.fromBase64Url(response),\n InvalidDcApiResponseError,\n 'encrypted response'\n )\n\n const sessionTranscript = await SessionTranscript.forIsoMdocDcApi(\n { encryptionInfoBase64Url: options.encryptionInfo, origin: options.origin },\n ctx\n )\n\n const plaintext = await hpke.open({\n suite: isoMdocDcApiHpkeSuite,\n recipientKey: options.recipientKey,\n enc: encryptedResponse.enc,\n info: sessionTranscript.encode(),\n ciphertext: encryptedResponse.ciphertext,\n })\n\n const deviceResponse = decodeOrThrow(\n () => DeviceResponse.decode(plaintext),\n InvalidDcApiResponseError,\n 'device response'\n )\n\n return { deviceResponse, sessionTranscript }\n }\n\n /**\n * Decrypt and verify an Annex C response (verifier side).\n */\n public static async verifyResponse(\n options: {\n response: IsoMdocDcApiResponse | string\n origin: string\n encryptionInfo: string\n recipientKey: CoseKey\n deviceRequest?: DeviceRequest\n deviceRequestMatchOptions?: DeviceRequestMatchOptions\n trustedCertificates: Array<{ issuance: Array<Uint8Array>; status?: Array<Uint8Array> }>\n disableCertificateChainValidation?: boolean\n disableStatusValidation?: boolean\n onCheck?: VerificationCallback\n now?: Date\n skewSeconds?: number\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose' | 'x509' | 'fetch'>\n ): Promise<{\n deviceResponse: DeviceResponse\n verificationResult: DeviceResponseVerificationResult\n }> {\n const { deviceResponse, sessionTranscript } = await IsoMdocDcApi.decryptResponse(options, ctx)\n\n const verificationResult = await deviceResponse.verify(\n {\n deviceRequest: options.deviceRequest,\n deviceRequestMatchOptions: options.deviceRequestMatchOptions,\n sessionTranscript,\n trustedCertificates: options.trustedCertificates,\n disableCertificateChainValidation: options.disableCertificateChainValidation,\n disableStatusValidation: options.disableStatusValidation,\n onCheck: options.onCheck,\n now: options.now,\n skewSeconds: options.skewSeconds,\n },\n ctx\n )\n\n return { deviceResponse, verificationResult }\n }\n}\n\nfunction assertHpke(ctx: Pick<MdocContext, 'crypto'>) {\n const { hpke } = ctx.crypto\n if (!hpke) {\n throw new HpkeNotSupportedError('The mdoc context does not provide HPKE support')\n }\n\n if (!hpke.suites.includes(isoMdocDcApiHpkeSuite)) {\n throw new HpkeNotSupportedError(`The mdoc context does not support HPKE suite '${isoMdocDcApiHpkeSuite}'`)\n }\n\n return hpke\n}\n\nfunction assertP256PublicKey(coseKey: CoseKey) {\n if (coseKey.keyType !== KeyType.Ec || coseKey.curve !== Curve['P-256']) {\n throw new InvalidEncryptionInfoError('Recipient public key must be an EC P-256 key')\n }\n}\n\n/**\n * The origin must be an ASCII serialized origin, as the DC API provides it (C.5), for instance\n * `https://verifier.example.com`. The session transcript binds the exact string, so for instance a\n * trailing slash would silently produce a transcript the other party does not compute.\n */\nfunction assertSerializedOrigin(origin: string) {\n let serializedOrigin: string | undefined\n try {\n serializedOrigin = new URL(origin).origin\n } catch {\n serializedOrigin = undefined\n }\n\n if (serializedOrigin === undefined || serializedOrigin === 'null' || serializedOrigin !== origin) {\n throw new InvalidOriginError(\n serializedOrigin && serializedOrigin !== 'null'\n ? `Origin '${origin}' is not a serialized origin, did you mean '${serializedOrigin}'?`\n : `Origin '${origin}' is not a serialized origin`\n )\n }\n}\n\n/**\n * Decode untrusted CBOR, surfacing a decoding failure as the DC API error for that payload.\n */\nfunction decodeOrThrow<Decoded>(\n decode: () => Decoded,\n ErrorClass: new (message: string) => Error,\n description: string\n): Decoded {\n try {\n return decode()\n } catch (error) {\n throw new ErrorClass(`Invalid ${description}: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\n/**\n * Parse untrusted input, surfacing a validation failure as the DC API error for that payload.\n */\nfunction parseOrThrow<Schema extends z.ZodType>(\n schema: Schema,\n data: unknown,\n ErrorClass: new (message: string) => Error,\n description: string\n): z.output<Schema> {\n const result = schema.safeParse(data)\n if (!result.success) {\n throw new ErrorClass(`Invalid ${description}: ${z.prettifyError(result.error)}`)\n }\n\n return result.data\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 DeviceRequest,\n DeviceResponse,\n type DeviceResponseVerificationResult,\n type SessionTranscript,\n} from './mdoc/index.js'\nimport {\n type DeviceRequestMatchOptions,\n type DeviceRequestMatchResult,\n matchDeviceRequest,\n} from './utils/matchDeviceRequest.js'\n\n// biome-ignore lint/complexity/noStaticOnlyClass: part of the public API\nexport class Verifier {\n public static async verifyDeviceResponse(\n options: {\n deviceRequest?: DeviceRequest\n deviceRequestMatchOptions?: DeviceRequestMatchOptions\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 : DeviceResponse.decode(options.deviceResponse)\n\n return deviceResponse.verify(options, ctx)\n }\n\n /**\n * Match a device response against the device request it answers, without verifying it. See\n * {@link matchDeviceRequest} for what is matched.\n *\n * `Verifier.verifyDeviceResponse` runs the same match as part of verification when a\n * `deviceRequest` is passed, reporting it through `onCheck` and returning it as\n * `deviceRequestMatch`.\n */\n public static matchDeviceRequest(options: {\n deviceRequest: Uint8Array | DeviceRequest\n deviceResponse: Uint8Array | DeviceResponse\n matchOptions?: DeviceRequestMatchOptions\n }): DeviceRequestMatchResult {\n return matchDeviceRequest({\n matchOptions: options.matchOptions,\n deviceRequest:\n options.deviceRequest instanceof DeviceRequest\n ? options.deviceRequest\n : DeviceRequest.decode(options.deviceRequest),\n deviceResponse:\n options.deviceResponse instanceof DeviceResponse\n ? options.deviceResponse\n : DeviceResponse.decode(options.deviceResponse),\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;AAWA,IAAY,cAAL,yBAAA,aAAA;;CAEL,YAAA,4CAAA;;CAGA,YAAA,4CAAA;;CAGA,YAAA,8CAAA;;AACF,EAAA,CAAA,CAAA;;;ACjBA,IAAa,WAAb,cAA8B,MAAM;CAClC,YAAY,UAAkB,WAAW,MAAM;EAC7C,MAAM,OAAO;CACf;AACF;AAEA,IAAa,gBAAb,cAAmC,SAAS,CAAC;AAC7C,IAAa,0CAAb,cAA6D,SAAS,CAAC;;;;;;AAOvE,IAAa,8BAAb,cAAiD,SAAS,CAAC;;;;;;AAO3D,IAAa,+BAAb,cAAkD,SAAS,CAAC;;;;;;AAO5D,IAAa,+BAAb,cAAkD,SAAS,CAAC;;;;;AAM5D,IAAa,uBAAb,cAA0C,SAAS,CAAC;;;;;;;AAQpD,IAAa,4BAAb,cAA+C,SAAS,CAAC;;;;;AAMzD,IAAa,wCAAb,cAA2D,SAAS,CAAC;AACrE,IAAa,qCAAb,cAAwD,SAAS,CAAC;;;;;AAMlE,IAAa,kCAAb,cAAqD,SAAS,CAAC;;;;;AAM/D,IAAa,2BAAb,cAA8C,SAAS,CAAC;;;;AAKxD,IAAa,qCAAb,cAAwD,SAAS,CAAC;AAClE,IAAa,yDAAb,cAA4E,SAAS,CAAC;AACtF,IAAa,qCAAb,cAAwD,SAAS,CAAC;AAClE,IAAa,kCAAb,cAAqD,SAAS,CAAC;AAC/D,IAAa,wBAAb,cAA2C,SAAS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