@owf/mdoc 0.10.0 → 0.11.0-alpha-20261116170607

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["z","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","z","z","z","z","Sign1","z","z","z","z","StatusListInfo","z","z","z","RegisteredCwtHeaderClaimKey","ProtectedHeaders","z","RegisteredCwtClaimKey","ProtectedHeaders","RegisteredCwtHeaderClaimKey","SignatureAlgorithm","verifyTokenStatusListJwt","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/alternative-data-elements-set.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/structureArray.ts","../src/utils/zodInteger.ts","../src/mdoc/models/use-case.ts","../src/mdoc/models/device-request-info.ts","../src/utils/ageOver.ts","../src/mdoc/models/doc-request-info.ts","../src/mdoc/models/items-request.ts","../src/mdoc/models/reader-authentication.ts","../src/mdoc/models/reader-auth.ts","../src/mdoc/models/doc-request.ts","../src/mdoc/models/device-request.ts","../src/utils/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/attribution.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'\nimport type { FetchCallback, FetchContext, FetchLimits } from '@owf/identity-common'\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\n/**\n * What a {@link MdocContext.fetch} call is retrieving. Lets an implementation apply policy —\n * caching, timeouts, retries — per resource rather than to every request alike.\n */\nexport type MdocFetchContext = FetchContext<MdocFetchType>\n\n/** What this library fetches: the status lists and identifier lists an MSO references. */\nexport type MdocFetchType = 'statusList' | 'identifierList'\n\nexport interface MdocContext {\n /**\n * Retrieves a resource over HTTP. `context` names what is being retrieved; the revocation lists\n * an MSO references are the only resources this library fetches. The body of the response is\n * read within {@link MdocContext.fetchLimits}, so `fetch` does not have to limit it.\n *\n * The global `fetch` satisfies this, as it ignores the third argument.\n */\n fetch: FetchCallback<MdocFetchType>\n\n /**\n * The maximum sizes of the status list and identifier list responses, 16 MiB each by default\n * (see `FetchLimits` of `@owf/identity-common`).\n */\n fetchLimits?: FetchLimits<MdocFetchType>\n\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 the path it validated with the leaf first and the\n * trusted root last.\n *\n * Only return the certificates of that path. The x5chain is in the unprotected header, so a\n * holder can add any certificate to it, and the `issuerIdentifiers` of a doc request are matched\n * against every certificate returned here: returning the whole x5chain with the trusted root\n * appended lets a document pass for any issuer whose certificate is added to it.\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 { IdentityError } from '@owf/identity-common'\nimport type { VerificationAssessment, VerificationCallback } from './check-callback.js'\n\n// biome-ignore format: no explanation\nexport class MdlError extends IdentityError {\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 * The documents of a device response do not answer the device request the way its request\n * information asks (ISO/IEC TS 23220-4 7.2.1.3): a document comes from an issuer the doc request\n * does not accept, more than one document answers a doc request that requires a unique document\n * set, the documents leave a mandatory use case of the device request unsatisfied, or every use\n * case, or the response is larger than the reader accepts.\n */\nexport class UnsatisfiedDeviceRequestError 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 UnableToExtractX5ChainFromJwtError extends MdlError {}\nexport class NoPublicKeySetOnStatusListError extends MdlError {}\nexport class InvalidSignatureError extends MdlError {}\n\n/**\n * RFC 9360: the end-entity certificate \"MUST be integrity protected by COSE\". An `x5chain` in the\n * unprotected header is therefore only accepted when a protected `x5t` matches its leaf.\n */\nexport class UnprotectedX5ChainNotBoundError extends MdlError {}\n\n/**\n * @deprecated A status list served as a JWT is now verified as a fallback rather than rejected, so\n * this error is no longer thrown.\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 — could not be used. Either one of the\n * claim requirements from ISO/IEC 18013-5 second edition 12.3.6 / the Token Status List\n * specification was not met (missing or mismatched subject, missing or passed expiration, or an\n * issuance time in the future), or a status list served as a JWT is malformed: not a well-formed\n * JWS, an unsupported `alg` or a `crit` header, or no readable `status_list`. Most of those JWT\n * checks run before the signature is verified, so this error does not by itself mean the list was\n * signed by its issuer.\n */\nexport class InvalidRevocationListError extends MdlError {}\n\n/**\n * The status list was verified, but the status of the MSO in it is not Valid, which ISO/IEC\n * 18013-5 second edition 12.3.6.1 requires. Unlike a list that fails verification, this is a\n * statement about the mdoc (Token Status List § 7 and § 8.3), so `uri`, `idx` and `status` are\n * carried as data rather than only in the message. It extends `InvalidRevocationListError`,\n * which a status that is not Valid was reported as before.\n */\nexport class StatusListEntryNotValidError extends InvalidRevocationListError {\n public readonly uri: string\n public readonly idx: number\n /** The status at `idx`, e.g. `1` for Invalid (revoked) or `2` for Suspended. */\n public readonly status: number\n\n public constructor(message: string, { uri, idx, status }: { uri: string; idx: number; status: number }) {\n super(message)\n this.uri = uri\n this.idx = idx\n this.status = status\n }\n}\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, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport type { Namespace } from './namespace'\n\n/**\n * A data element, by namespace and identifier (ISO/IEC TS 23220-4 7.2.1.3.2 `ElementReference`).\n */\nexport type ElementReference = [Namespace, DataElementIdentifier]\n\nconst zElementReference = z.tuple([z.string(), z.string()])\n\nconst zAlternativeDataElementsSet = typedMap([\n ['requestedElement', zElementReference],\n ['alternativeElementSets', z.array(z.array(zElementReference).min(1)).min(1)],\n] as const)\n\nexport type AlternativeDataElementsSetEncodedStructure = z.input<typeof zAlternativeDataElementsSet>\nexport type AlternativeDataElementsSetDecodedStructure = z.output<typeof zAlternativeDataElementsSet>\n\nexport type AlternativeDataElementsSetOptions = {\n requestedElement: ElementReference\n /**\n * The sets of elements that may be returned in place of the requested one, in the reader's order\n * of preference.\n */\n alternativeElementSets: Array<Array<ElementReference>>\n}\n\n/**\n * Elements that may be returned in place of a requested one (ISO/IEC TS 23220-4 7.2.1.3.2). Each set\n * answers the request on its own; the sets are in the reader's order of preference, the most\n * privacy-preserving first.\n */\nexport class AlternativeDataElementsSet extends CborStructure<\n AlternativeDataElementsSetEncodedStructure,\n AlternativeDataElementsSetDecodedStructure\n> {\n public static override get encodingSchema() {\n return zAlternativeDataElementsSet\n }\n\n public get requestedElement(): ElementReference {\n return this.structure.get('requestedElement')\n }\n\n public get alternativeElementSets(): Array<Array<ElementReference>> {\n return this.structure.get('alternativeElementSets')\n }\n\n public static create(options: AlternativeDataElementsSetOptions): AlternativeDataElementsSet {\n const map: AlternativeDataElementsSetDecodedStructure = new TypedMap([\n ['requestedElement', options.requestedElement],\n ['alternativeElementSets', options.alternativeElementSets],\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, 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 zBleOptions = 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 zBleOptions>\nexport type BleOptionsDecodedStructure = z.output<typeof zBleOptions>\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 zBleOptions\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 | {\n type: 'deviceRequestMatch'\n match: DeviceRequestMatchResult\n }\n | {\n /** The status of the MSO in its status list is not Valid. */\n type: 'statusListEntryNotValid'\n uri: string\n idx: number\n /** The status at `idx`, e.g. `1` for Invalid (revoked) or `2` for Suspended. */\n status: number\n }\n | {\n /** The identifier of the MSO is in its identifier list. */\n type: 'identifierListEntryRevoked'\n uri: string\n id: Uint8Array\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 zDeviceSignedItems = z.map(z.string(), z.unknown())\n\nexport type DeviceSignedItemsStructure = z.infer<typeof zDeviceSignedItems>\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 zDeviceSignedItems\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, zDeviceSignedItems } from './device-signed-items'\nimport type { Namespace } from './namespace'\n\nconst zDeviceNamespacesEncoded = z.map(z.string(), zDeviceSignedItems)\nconst zDeviceNamespacesDecoded = z.map(z.string(), z.instanceof(DeviceSignedItems))\n\nexport type DeviceNamespacesDecodedStructure = z.infer<typeof zDeviceNamespacesDecoded>\nexport type DeviceNamespacesEncodedStructure = z.infer<typeof zDeviceNamespacesEncoded>\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(zDeviceNamespacesEncoded, zDeviceNamespacesDecoded, {\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 zNfcOptions = typedMap([\n [NfcOptionsKeys.MaxCommandDataLength, z.number()],\n [NfcOptionsKeys.MaxResponseDataLength, z.number()],\n] as const)\n\nexport type NfcOptionsEncodedStructure = z.input<typeof zNfcOptions>\nexport type NfcOptionsDecodedStructure = z.output<typeof zNfcOptions>\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 zNfcOptions\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 zWifiOptions = 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 zWifiOptions>\nexport type WifiOptionsDecodedStructure = z.output<typeof zWifiOptions>\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 zWifiOptions\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 zDeviceRetrievalMethodEncoded = z.tuple([\n z.enum(DeviceRetrievalMethodType).or(z.number()),\n z.number(),\n z.map(z.unknown(), z.unknown()),\n])\n\nconst zDeviceRetrievalMethodDecoded = 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 zDeviceRetrievalMethodEncoded>\nexport type DeviceRetrievalMethodDecodedStructure = z.infer<typeof zDeviceRetrievalMethodDecoded>\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(zDeviceRetrievalMethodEncoded, zDeviceRetrievalMethodDecoded, {\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 zProtocolInfo = z.unknown()\nexport type ProtocolInfoStructure = z.infer<typeof zProtocolInfo>\n\nexport class ProtocolInfo extends CborStructure<ProtocolInfoStructure> {\n public static override get encodingSchema() {\n return zProtocolInfo\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 zSecurityEncoded = z.tuple([z.number(), z.instanceof(DataItem)])\n\nconst zSecurityDecoded = z.object({\n cipherSuiteIdentifier: z.number(),\n eDeviceKey: z.instanceof(EDeviceKey),\n})\n\nexport type SecurityEncodedStructure = z.infer<typeof zSecurityEncoded>\nexport type SecurityDecodedStructure = z.infer<typeof zSecurityDecoded>\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(zSecurityEncoded, zSecurityDecoded, {\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 zOidcEncoded = z.tuple([z.number(), z.string(), z.string()])\n\n// Easier structure for internal usage in class\nconst zOidcDecoded = z.object({\n version: z.number(),\n issuerUrl: z.string(),\n serverRetrievalToken: z.string(),\n})\n\nexport type OidcEncodedStructure = z.infer<typeof zOidcEncoded>\nexport type OidcDecodedStructure = z.infer<typeof zOidcDecoded>\nexport type OidcOptions = OidcDecodedStructure\n\nexport class Oidc extends CborStructure<OidcEncodedStructure, OidcDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(zOidcEncoded, zOidcDecoded, {\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 zWebApiEncoded = z.tuple([z.number(), z.string(), z.string()])\n\n// Easier structure for internal usage in class\nconst zWebApiDecoded = z.object({\n version: z.number(),\n issuerUrl: z.string(),\n serverRetrievalToken: z.string(),\n})\n\nexport type WebApiEncodedStructure = z.infer<typeof zWebApiEncoded>\nexport type WebApiDecodedStructure = z.infer<typeof zWebApiDecoded>\nexport type WebApiOptions = WebApiDecodedStructure\n\nexport class WebApi extends CborStructure<WebApiEncodedStructure, WebApiDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(zWebApiEncoded, zWebApiDecoded, {\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 zServerRetrievalMethod = typedMap([\n ['webApi', z.instanceof(WebApi).exactOptional()],\n ['oidc', z.instanceof(Oidc).exactOptional()],\n] as const)\n\nexport type ServerRetrievalMethodDecodedStructure = z.output<typeof zServerRetrievalMethod>\nexport type ServerRetrievalMethodEncodedStructure = z.input<typeof zServerRetrievalMethod>\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(zServerRetrievalMethod.in, zServerRetrievalMethod.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 zDeviceEngagement = 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 zDeviceEngagement>\nexport type DeviceEngagementDecodedStructure = z.output<typeof zDeviceEngagement>\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(zDeviceEngagement.in, zDeviceEngagement.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 zEngagementToAppHandover = zUint8Array\nexport type EngagementToAppHandoverStructure = z.infer<typeof zEngagementToAppHandover>\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 zEngagementToAppHandover\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 zIsoMdocDcApiHandoverEncoded = z.tuple([z.literal('dcapi'), zUint8Array])\nconst zIsoMdocDcApiHandoverDecoded = zUint8Array\n\nexport type IsoMdocDcApiHandoverEncodedStructure = z.infer<typeof zIsoMdocDcApiHandoverEncoded>\nexport type IsoMdocDcApiHandoverDecodedStructure = z.infer<typeof zIsoMdocDcApiHandoverDecoded>\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(zIsoMdocDcApiHandoverEncoded, zIsoMdocDcApiHandoverDecoded, {\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 zNfcHandoverEncoded = z.tuple([zUint8Array, zUint8Array.nullable()])\nconst zNfcHandoverDecoded = z.object({\n selectMessage: zUint8Array,\n requestMessage: zUint8Array.nullable(),\n})\n\nexport type NfcHandoverEncodedStructure = z.infer<typeof zNfcHandoverEncoded>\nexport type NfcHandoverDecodedStructure = z.infer<typeof zNfcHandoverDecoded>\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(zNfcHandoverEncoded, zNfcHandoverDecoded, {\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 zOid4vpDcApiDraft24HandoverInfo = z.tuple([z.string(), z.string(), z.string()])\nconst zOid4vpDcApiDraft24HandoverInfoDecoded = z.object({\n origin: z.string(),\n clientId: z.string(),\n nonce: z.string(),\n})\n\nexport type Oid4vpDcApiDraft24HandoverInfoEncodedStructure = z.infer<typeof zOid4vpDcApiDraft24HandoverInfo>\nexport type Oid4vpDcApiDraft24HandoverInfoDecodedStructure = z.infer<typeof zOid4vpDcApiDraft24HandoverInfoDecoded>\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(zOid4vpDcApiDraft24HandoverInfo, zOid4vpDcApiDraft24HandoverInfoDecoded, {\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 zOid4vpDcApiHandoverEncoded = z.tuple([z.literal('OpenID4VPDCAPIHandover'), zUint8Array])\nconst zOid4vpDcApiHandoverDecoded = zUint8Array\n\nexport type Oid4vpDcApiHandoverEncodedStructure = z.infer<typeof zOid4vpDcApiHandoverEncoded>\nexport type Oid4vpDcApiHandoverDecodedStructure = z.infer<typeof zOid4vpDcApiHandoverDecoded>\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(zOid4vpDcApiHandoverEncoded, zOid4vpDcApiHandoverDecoded, {\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 zOid4vpDcApiHandoverInfoEncoded = z.tuple([z.string(), z.string(), zUint8Array.nullable()])\nconst zOid4vpDcApiHandoverInfoDecoded = z.object({\n origin: z.string(),\n nonce: z.string(),\n jwkThumbprint: zUint8Array.nullable(),\n})\n\nexport type Oid4vpDcApiHandoverInfoEncodedStructure = z.infer<typeof zOid4vpDcApiHandoverInfoEncoded>\nexport type Oid4vpDcApiHandoverInfoDecodedStructure = z.infer<typeof zOid4vpDcApiHandoverInfoDecoded>\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(zOid4vpDcApiHandoverInfoEncoded, zOid4vpDcApiHandoverInfoDecoded, {\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 zOid4vpDraft18HandoverEncoded = z.tuple([zUint8Array, zUint8Array, z.string()])\nconst zOid4vpDraft18HandoverDecoded = z.object({\n clientIdHash: zUint8Array,\n responseUriHash: zUint8Array,\n nonce: z.string(),\n})\n\nexport type Oid4vpDraft18HandoverEncodedStructure = z.infer<typeof zOid4vpDraft18HandoverEncoded>\nexport type Oid4vpDraft18HandoverDecodedStructure = z.infer<typeof zOid4vpDraft18HandoverDecoded>\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(zOid4vpDraft18HandoverEncoded, zOid4vpDraft18HandoverDecoded, {\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 zOid4vpHandoverEncoded = z.tuple([z.literal('OpenID4VPHandover'), zUint8Array])\nconst zOid4vpHandoverDecoded = zUint8Array\n\nexport type Oid4vpHandoverEncodedStructure = z.infer<typeof zOid4vpHandoverEncoded>\nexport type Oid4vpHandoverDecodedStructure = z.infer<typeof zOid4vpHandoverDecoded>\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(zOid4vpHandoverEncoded, zOid4vpHandoverDecoded, {\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 zOid4vpHandoverInfoEncoded = z.tuple([z.string(), z.string(), zUint8Array.nullable(), z.string()])\nconst zOid4vpHandoverInfoDecoded = 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 zOid4vpHandoverInfoEncoded>\nexport type Oid4vpHandoverInfoDecodedStructure = z.infer<typeof zOid4vpHandoverInfoDecoded>\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(zOid4vpHandoverInfoEncoded, zOid4vpHandoverInfoDecoded, {\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 zOid4vpIaeHandoverEncoded = z.tuple([z.literal('OpenID4VCIIAEHandover'), zUint8Array])\nconst zOid4vpIaeHandoverDecoded = zUint8Array\n\nexport type Oid4vpIaeHandoverEncodedStructure = z.infer<typeof zOid4vpIaeHandoverEncoded>\nexport type Oid4vpIaeHandoverDecodedStructure = z.infer<typeof zOid4vpIaeHandoverDecoded>\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(zOid4vpIaeHandoverEncoded, zOid4vpIaeHandoverDecoded, {\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 zOid4vpIaeHandoverInfoEncoded = z.tuple([z.string(), z.string(), zUint8Array.nullable()])\nconst zOid4vpIaeHandoverInfoDecoded = z.object({\n interactiveAuthorizationEndpoint: z.string(),\n nonce: z.string(),\n jwkThumbprint: zUint8Array.nullable(),\n})\n\nexport type Oid4vpIaeHandoverInfoEncodedStructure = z.infer<typeof zOid4vpIaeHandoverInfoEncoded>\nexport type Oid4vpIaeHandoverInfoDecodedStructure = z.infer<typeof zOid4vpIaeHandoverInfoDecoded>\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(zOid4vpIaeHandoverInfoEncoded, zOid4vpIaeHandoverInfoDecoded, {\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 zQrHandover = z.null()\nexport type QrHandoverStructure = z.infer<typeof zQrHandover>\n\nexport class QrHandover extends Handover<QrHandoverStructure> {\n public static override get encodingSchema() {\n return zQrHandover\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 zSessionTranscriptEncoded = z.tuple([\n z.instanceof<typeof DataItem<DeviceEngagementEncodedStructure>>(DataItem).nullable(),\n z.instanceof<typeof DataItem<EReaderKeyEncodedStructure>>(DataItem).nullable(),\n z.unknown(),\n])\n\nconst zSessionTranscriptDecoded = 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 zSessionTranscriptDecoded>\nexport type SessionTranscriptEncodedStructure = z.infer<typeof zSessionTranscriptEncoded>\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(zSessionTranscriptEncoded, zSessionTranscriptDecoded, {\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, zSessionTranscriptEncoded } from './session-transcript'\n\nconst zDeviceAuthenticationEncoded = z.tuple([\n z.literal('DeviceAuthentication'),\n zSessionTranscriptEncoded,\n z.string(),\n z.instanceof<typeof DataItem<DeviceNamespacesEncodedStructure>>(DataItem),\n])\n\nconst zDeviceAuthenticationDecoded = z.object({\n sessionTranscript: z.instanceof(SessionTranscript),\n docType: z.string(),\n deviceNamespaces: z.instanceof(DeviceNamespaces),\n})\n\nexport type DeviceAuthenticationDecodedStructure = z.infer<typeof zDeviceAuthenticationDecoded>\nexport type DeviceAuthenticationEncodedStructure = z.infer<typeof zDeviceAuthenticationEncoded>\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(zDeviceAuthenticationEncoded, zDeviceAuthenticationDecoded, {\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 zDeviceAuth = 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 zDeviceAuthDecoded = zDeviceAuth.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 zDeviceAuth>\nexport type DeviceAuthEncodedStructure = z.input<typeof zDeviceAuth>\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(zDeviceAuth.in, zDeviceAuthDecoded, {\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 deviceSignature.verifySignature(\n { key: deviceKey, detachedPayload: deviceAuthenticationBytes },\n ctx.cose.sign1\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 zKeyAuthorizations = 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 zKeyAuthorizations>\nexport type KeyAuthorizationsDecodedStructure = z.output<typeof zKeyAuthorizations>\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 zKeyAuthorizations\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 zKeyInfo = z.map(z.number(), z.unknown())\n\nexport type KeyInfoEncodedStructure = z.input<typeof zKeyInfo>\nexport type KeyInfoDecodedStructure = z.output<typeof zKeyInfo>\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 zKeyInfo\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 zDeviceKeyInfo = 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 zDeviceKeyInfo>\nexport type DeviceKeyInfoEncodedStructure = z.input<typeof zDeviceKeyInfo>\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(zDeviceKeyInfo.in, zDeviceKeyInfo.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 { AnyTypedMap } from '@owf/cose'\n\n/**\n * `typedMap` decode and encode hooks for a key whose value is an array of nested structures, such as\n * the use cases of a `DeviceRequestInfo`. Decoding turns each encoded map into its structure with\n * `decode`, encoding turns each structure back into its encoded map. A value that is not an array is\n * left as is, for the schema to reject.\n */\nexport const structureArrayHooks = <Structure extends { encodedStructure: unknown }>(\n key: string,\n decode: (encoded: unknown) => Structure\n) => ({\n decode: (input: Map<unknown, unknown>, originalDecode: (input: Map<unknown, unknown>) => AnyTypedMap) => {\n const map = originalDecode(input)\n const value = input.get(key)\n if (Array.isArray(value)) map.set(key, value.map(decode))\n return map\n },\n encode: (output: AnyTypedMap, originalEncode: (output: AnyTypedMap) => Map<unknown, unknown>) => {\n const map = originalEncode(output)\n const value: unknown = output.get(key)\n if (Array.isArray(value))\n map.set(\n key,\n (value as Array<Structure>).map((structure) => structure.encodedStructure)\n )\n return map\n },\n})\n","import { z } from 'zod'\n\nconst MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER)\nconst MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER)\n\n/**\n * An integer as cbor-x decodes it: a number, or a bigint when the encoder wrote it in 8 bytes,\n * whatever its value. Only values a number holds exactly are accepted; read them with `Number()`.\n */\nexport const zInteger = z.union([z.number().int(), z.bigint().min(MIN_SAFE).max(MAX_SAFE)])\n\n/**\n * A non-negative {@link zInteger}, a CDDL `uint`.\n */\nexport const zUnsignedInteger = z.union([z.number().int().nonnegative(), z.bigint().nonnegative().max(MAX_SAFE)])\n","import { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { zInteger, zUnsignedInteger } from '../../utils/zodInteger'\n\nconst zUseCase = typedMap([\n ['mandatory', z.boolean()],\n ['purposeHints', z.map(z.string(), zInteger).exactOptional()],\n ['documentSets', z.array(z.array(zUnsignedInteger).min(1)).min(1)],\n] as const)\n\nexport type UseCaseEncodedStructure = z.input<typeof zUseCase>\nexport type UseCaseDecodedStructure = z.output<typeof zUseCase>\n\nexport type UseCaseOptions = {\n /**\n * Whether the use case has to be satisfied for the device request to be.\n */\n mandatory: boolean\n /**\n * Why the reader asks, per purpose controller, as codes of a registry a profile defines.\n */\n purposeHints?: Map<string, number>\n /**\n * The document sets that answer the use case, each a list of indexes into `docRequests`.\n */\n documentSets: Array<Array<number>>\n}\n\n/**\n * A use case of a device request (ISO/IEC TS 23220-4 7.2.1.3.4): the doc requests, by index into\n * `docRequests`, that answer it. Exactly one document set has to be returned for the use case to be\n * satisfied, every doc request of that set included.\n */\nexport class UseCase extends CborStructure<UseCaseEncodedStructure, UseCaseDecodedStructure> {\n public static override get encodingSchema() {\n return zUseCase\n }\n\n public get mandatory() {\n return this.structure.get('mandatory')\n }\n\n public get purposeHints(): Map<string, number> | undefined {\n const purposeHints = this.structure.get('purposeHints')\n return purposeHints && new Map(Array.from(purposeHints, ([controller, code]) => [controller, Number(code)]))\n }\n\n public get documentSets(): Array<Array<number>> {\n return this.structure.get('documentSets').map((set) => set.map(Number))\n }\n\n public static create(options: UseCaseOptions): UseCase {\n const map: UseCaseDecodedStructure = new TypedMap([['mandatory', options.mandatory]])\n if (options.purposeHints) map.set('purposeHints', options.purposeHints)\n map.set('documentSets', options.documentSets)\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 { structureArrayHooks } from '../../utils/structureArray'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\nimport { UseCase, type UseCaseEncodedStructure, type UseCaseOptions } from './use-case'\n\nconst zDeviceRequestInfo = typedMap(\n [['useCases', z.array(z.instanceof(UseCase)).min(1).exactOptional()]] as const,\n structureArrayHooks('useCases', (useCase) => UseCase.fromEncodedStructure(useCase as UseCaseEncodedStructure))\n)\n\nexport type DeviceRequestInfoEncodedStructure = z.input<typeof zDeviceRequestInfo>\nexport type DeviceRequestInfoDecodedStructure = z.output<typeof zDeviceRequestInfo>\n\nexport type DeviceRequestInfoOptions = {\n useCases?: Array<UseCase | UseCaseOptions>\n}\n\n/**\n * Information on a device request as a whole, the `deviceRequestInfo` of a `DeviceRequest`\n * (ISO/IEC TS 23220-4 7.2.1.3.4, taken up by the second edition of ISO/IEC 18013-5): which doc\n * requests answer which use case.\n *\n * Embedded as `DeviceRequestInfoBytes` (tag 24), so the bytes are kept as received.\n */\nexport class DeviceRequestInfo extends OriginalBytesCborStructure<\n DeviceRequestInfoEncodedStructure,\n DeviceRequestInfoDecodedStructure\n> {\n public static override get encodingSchema() {\n return zDeviceRequestInfo\n }\n\n public get useCases() {\n return this.structure.get('useCases')\n }\n\n public static create(options: DeviceRequestInfoOptions): DeviceRequestInfo {\n const map: DeviceRequestInfoDecodedStructure = new TypedMap([])\n\n if (options.useCases !== undefined) {\n map.set(\n 'useCases',\n options.useCases.map((useCase) => (useCase instanceof UseCase ? useCase : UseCase.create(useCase)))\n )\n }\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 { CborStructure, TypedMap, typedMap, zUint8Array } from '@owf/cose'\nimport { z } from 'zod'\nimport { structureArrayHooks } from '../../utils/structureArray'\nimport { zUnsignedInteger } from '../../utils/zodInteger'\nimport {\n AlternativeDataElementsSet,\n type AlternativeDataElementsSetEncodedStructure,\n type AlternativeDataElementsSetOptions,\n} from './alternative-data-elements-set'\n\nconst zDocRequestInfo = typedMap(\n [\n ['alternativeDataElements', z.array(z.instanceof(AlternativeDataElementsSet)).min(1).exactOptional()],\n ['issuerIdentifiers', z.array(zUint8Array).min(1).exactOptional()],\n ['uniqueDocSetRequired', z.boolean().exactOptional()],\n ['maximumResponseSize', zUnsignedInteger.exactOptional()],\n ] as const,\n structureArrayHooks('alternativeDataElements', (set) =>\n AlternativeDataElementsSet.fromEncodedStructure(set as AlternativeDataElementsSetEncodedStructure)\n )\n)\n\nexport type DocRequestInfoEncodedStructure = z.input<typeof zDocRequestInfo>\nexport type DocRequestInfoDecodedStructure = z.output<typeof zDocRequestInfo>\n\nexport type DocRequestInfoOptions = {\n alternativeDataElements?: Array<AlternativeDataElementsSet | AlternativeDataElementsSetOptions>\n /**\n * Key identifiers of the authority key identifier of an acceptable issuer certificate. An mdoc\n * only satisfies the doc request when one of them is the authority key identifier of a certificate\n * in its chain: for a verifier the chain it validated, as the x5chain is unprotected, and for a\n * holder the x5chain of its IssuerAuth.\n */\n issuerIdentifiers?: Array<Uint8Array>\n uniqueDocSetRequired?: boolean\n /**\n * The largest unencrypted DeviceResponse, in bytes, the reader accepts.\n */\n maximumResponseSize?: number\n /**\n * Entries a profile adds to `requestInfo`, such as the `euWrprc` registration certificate of ETSI TS\n * 119 472-2 clause 5.3.2. The entries above take precedence over one with the same key.\n */\n extensions?: Record<string, unknown>\n}\n\n/**\n * Additional information on a doc request, the `requestInfo` of an `ItemsRequest` (ISO/IEC TS\n * 23220-4 7.2.1.3.2, taken up by the second edition of ISO/IEC 18013-5).\n *\n * Keys this structure does not know are kept, so that an `ItemsRequest` re-encodes as received.\n */\nexport class DocRequestInfo extends CborStructure<DocRequestInfoEncodedStructure, DocRequestInfoDecodedStructure> {\n public static override get encodingSchema() {\n return zDocRequestInfo\n }\n\n public get alternativeDataElements() {\n return this.structure.get('alternativeDataElements')\n }\n\n public get issuerIdentifiers() {\n return this.structure.get('issuerIdentifiers')\n }\n\n public get uniqueDocSetRequired() {\n return this.structure.get('uniqueDocSetRequired')\n }\n\n public get maximumResponseSize() {\n const maximumResponseSize = this.structure.get('maximumResponseSize')\n return maximumResponseSize === undefined ? undefined : Number(maximumResponseSize)\n }\n\n /**\n * An entry of `requestInfo` by key, such as a profile extension. An entry this structure does not\n * define is returned as decoded, without validation.\n */\n public getExtension(key: string): unknown {\n return this.structure.get(key as never)\n }\n\n public static create(options: DocRequestInfoOptions): DocRequestInfo {\n const map: DocRequestInfoDecodedStructure = TypedMap.fromObject(options.extensions ?? {})\n\n if (options.alternativeDataElements !== undefined) {\n map.set(\n 'alternativeDataElements',\n options.alternativeDataElements.map((set) =>\n set instanceof AlternativeDataElementsSet ? set : AlternativeDataElementsSet.create(set)\n )\n )\n }\n if (options.issuerIdentifiers !== undefined) map.set('issuerIdentifiers', options.issuerIdentifiers)\n if (options.uniqueDocSetRequired !== undefined) map.set('uniqueDocSetRequired', options.uniqueDocSetRequired)\n if (options.maximumResponseSize !== undefined) map.set('maximumResponseSize', options.maximumResponseSize)\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 { describeAgeOverLimitViolations, findAgeOverRequestLimitViolations } from '../../utils/ageOver'\nimport { AgeOverLimitExceededError } from '../errors'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport { DocRequestInfo, type DocRequestInfoOptions } from './doc-request-info'\nimport type { DocType } from './doctype'\nimport type { IntentToRetain } from './intent-to-retain'\nimport type { Namespace } from './namespace'\n\nconst zNamespaces = z.map(z.string(), z.map(z.string(), z.boolean()))\n\n// Zod schema for ItemsRequest\nconst zItemsRequest = typedMap(\n [\n ['docType', z.string()],\n ['nameSpaces', zNamespaces],\n ['requestInfo', z.instanceof(DocRequestInfo).exactOptional()],\n ] as const,\n {\n decode: (input, originalDecode) => {\n const map = originalDecode(input)\n // Anything but a map is left for the schema to reject.\n const requestInfo = input.get('requestInfo')\n if (requestInfo instanceof Map) map.set('requestInfo', DocRequestInfo.fromEncodedStructure(requestInfo))\n return map\n },\n encode: (output, originalEncode) => {\n const map = originalEncode(output)\n const requestInfo = output.get('requestInfo')\n if (requestInfo) map.set('requestInfo', requestInfo.encodedStructure)\n return map\n },\n }\n)\n\nexport type ItemsRequestEncodedStructure = z.input<typeof zItemsRequest>\nexport type ItemsRequestDecodedStructure = z.output<typeof zItemsRequest>\n\ntype NamespacesStructure = z.infer<typeof zNamespaces>\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 requestInfo?: DocRequestInfo | DocRequestInfoOptions\n}\n\nexport class ItemsRequest extends OriginalBytesCborStructure<\n ItemsRequestEncodedStructure,\n ItemsRequestDecodedStructure\n> {\n public static override get encodingSchema() {\n return zItemsRequest\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 * The `requestInfo` of ISO/IEC TS 23220-4 7.2.1.3.2.\n */\n public get requestInfo() {\n return this.structure.get('requestInfo')\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: ItemsRequestDecodedStructure = new TypedMap([\n ['docType', options.docType],\n ['nameSpaces', namespaces],\n ])\n if (options.requestInfo) {\n structure.set(\n 'requestInfo',\n options.requestInfo instanceof DocRequestInfo ? options.requestInfo : DocRequestInfo.create(options.requestInfo)\n )\n }\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(structure)\n }\n}\n","import { CborStructure, DataItem } from '@owf/cose'\nimport { z } from 'zod'\nimport { ItemsRequest, type ItemsRequestEncodedStructure } from './items-request'\nimport { SessionTranscript, zSessionTranscriptEncoded } from './session-transcript'\n\nconst zReaderAuthenticationEncoded = z.tuple([\n z.literal('ReaderAuthentication'),\n zSessionTranscriptEncoded,\n z.instanceof<typeof DataItem<ItemsRequestEncodedStructure>>(DataItem),\n])\n\nconst zReaderAuthenticationDecoded = z.object({\n sessionTranscript: z.instanceof(SessionTranscript),\n itemsRequest: z.instanceof(ItemsRequest),\n})\n\nexport type ReaderAuthenticationDecodedStructure = z.infer<typeof zReaderAuthenticationDecoded>\nexport type ReaderAuthenticationEncodedStructure = z.infer<typeof zReaderAuthenticationEncoded>\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(zReaderAuthenticationEncoded, zReaderAuthenticationDecoded, {\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, verifyX5t } 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' | 'crypto'>\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 // ISO/IEC 18013-5 (second edition) § 12.5.4: an x5t, if present, shall use SHA-256.\n const x5tCheck = 'The x5t in the protected header, if present, must be SHA-256 and match the reader certificate'\n try {\n await verifyX5t(this, this.certificate, ctx.crypto)\n onCheck({ status: 'PASSED', check: x5tCheck })\n } catch (err) {\n onCheck({ status: 'FAILED', check: x5tCheck, reason: err instanceof Error ? err.message : 'Unknown error' })\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 zDocRequest = typedMap([\n ['itemsRequest', z.instanceof(ItemsRequest)],\n ['readerAuth', z.instanceof(ReaderAuth).exactOptional()],\n] as const)\n\nexport type DocRequestDecodedStructure = z.output<typeof zDocRequest>\nexport type DocRequestEncodedStructure = z.input<typeof zDocRequest>\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(zDocRequest.in, zDocRequest.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, DataItem, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { DeviceRequestInfo, type DeviceRequestInfoOptions } from './device-request-info'\nimport { DocRequest, type DocRequestEncodedStructure } from './doc-request'\n\nconst zDeviceRequest = typedMap([\n ['version', z.string()],\n ['docRequests', z.array(z.instanceof(DocRequest))],\n ['deviceRequestInfo', z.instanceof(DeviceRequestInfo).exactOptional()],\n] as const)\n\n// Every document set of a use case points at doc requests of this device request.\nconst zDeviceRequestOutput = zDeviceRequest.out.superRefine((map, ctx) => {\n // A missing or invalid docRequests is reported by the schema itself.\n const docRequests: unknown = map.get('docRequests')\n if (!Array.isArray(docRequests)) return\n const docRequestCount = docRequests.length\n map.get('deviceRequestInfo')?.useCases?.forEach((useCase, useCaseIndex) => {\n const missing = Array.from(new Set(useCase.documentSets.flat())).filter((id) => id >= docRequestCount)\n if (missing.length === 0) return\n ctx.addIssue({\n code: 'custom',\n path: ['deviceRequestInfo', 'useCases', useCaseIndex, 'documentSets'],\n message: `Doc request ${missing.join(', ')} ${missing.length === 1 ? 'does' : 'do'} not exist, the device request has ${docRequestCount}`,\n })\n })\n})\n\nexport type DeviceRequestDecodedStructure = z.output<typeof zDeviceRequest>\nexport type DeviceRequestEncodedStructure = z.input<typeof zDeviceRequest>\n\nexport type DeviceRequestOptions = {\n /**\n * Defaults to `'1.1'` when `deviceRequestInfo` is given and to `'1.0'` otherwise, as the second\n * edition of ISO/IEC 18013-5 asks (10.2.2).\n */\n version?: string\n docRequests: Array<DocRequest>\n deviceRequestInfo?: DeviceRequestInfo | DeviceRequestInfoOptions\n}\n\nexport class DeviceRequest extends CborStructure<DeviceRequestEncodedStructure, DeviceRequestDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(zDeviceRequest.in, zDeviceRequestOutput, {\n decode: (input) => {\n const map: DeviceRequestDecodedStructure = TypedMap.fromMap(input)\n // Anything but an array is left for the schema to reject.\n const docRequests = input.get('docRequests')\n if (Array.isArray(docRequests)) {\n map.set(\n 'docRequests',\n docRequests.map((dr) => DocRequest.fromEncodedStructure(dr as DocRequestEncodedStructure))\n )\n }\n\n // Anything but a data item is left for the schema to reject.\n const deviceRequestInfo = input.get('deviceRequestInfo')\n if (deviceRequestInfo instanceof DataItem) {\n map.set('deviceRequestInfo', DeviceRequestInfo.fromDataItem(deviceRequestInfo))\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 const deviceRequestInfo = output.get('deviceRequestInfo')\n if (deviceRequestInfo) map.set('deviceRequestInfo', deviceRequestInfo.asDataItem)\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 /**\n * The `deviceRequestInfo` of ISO/IEC TS 23220-4 7.2.1.3.4.\n */\n public get deviceRequestInfo() {\n return this.structure.get('deviceRequestInfo')\n }\n\n public static create(options: DeviceRequestOptions): DeviceRequest {\n const deviceRequestInfo =\n options.deviceRequestInfo instanceof DeviceRequestInfo || options.deviceRequestInfo === undefined\n ? options.deviceRequestInfo\n : DeviceRequestInfo.create(options.deviceRequestInfo)\n\n const map: DeviceRequestDecodedStructure = new TypedMap([\n ['version', options.version ?? (deviceRequestInfo ? '1.1' : '1.0')],\n ['docRequests', options.docRequests],\n ])\n if (deviceRequestInfo) map.set('deviceRequestInfo', deviceRequestInfo)\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 zIdentifierListInfo = typedMap([\n ['id', zUint8Array],\n ['uri', z.string()],\n ['certificate', zUint8Array.exactOptional()],\n])\n\nexport type IdentifierListInfoDecodedStructure = z.output<typeof zIdentifierListInfo>\nexport type IdentifierListInfoEncodedStructure = z.input<typeof zIdentifierListInfo>\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 zIdentifierListInfo\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 zStatus = typedMap([\n ['status_list', z.instanceof(StatusListInfo).exactOptional()],\n ['identifier_list', z.instanceof(IdentifierListInfo).exactOptional()],\n])\n\nexport type StatusDecodedStructure = z.output<typeof zStatus>\nexport type StatusEncodedStructure = z.input<typeof zStatus>\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(zStatus.in, zStatus.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 zValidityInfo = 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 zValidityInfo>\nexport type ValidityInfoDecodedStructure = z.output<typeof zValidityInfo>\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 zValidityInfo\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 zValueDigests = z.map(z.string(), z.map(z.number(), zUint8Array))\n\nexport type ValueDigestsStructure = z.infer<typeof zValueDigests>\n\nexport type ValueDigestOptions = {\n digests: ValueDigestsStructure\n}\n\nexport class ValueDigests extends CborStructure<ValueDigestsStructure> {\n public static override get encodingSchema() {\n return zValueDigests\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 zMobileSecurityObject = 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 zMobileSecurityObject>\nexport type MobileSecurityObjectEncodedStructure = z.input<typeof zMobileSecurityObject>\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(zMobileSecurityObject.in, zMobileSecurityObject.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 const MdocMediaTypes = {\n IdentifierListCwt: 'application/identifierlist+cwt',\n} as const\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(MdocMediaTypes.IdentifierListCwt, {\n error: `Typ (protected header 16) shall be '${MdocMediaTypes.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 zIdentifierInfo = z.map(z.union([z.string(), z.number()]), z.unknown())\n\nconst zIdentifierList = typedMap(\n [\n ['identifiers', z.map(zUint8Array, zIdentifierInfo)],\n ['aggregation_uri', z.string().exactOptional()],\n ],\n { allowAdditionalKeys: true }\n)\n\nexport type IdentifierListDecodedStructure = z.output<typeof zIdentifierList>\nexport type IdentifierListEncodedStructure = z.input<typeof zIdentifierList>\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 zIdentifierList\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 zIdentifierListCwtPayload = 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 zIdentifierListCwtPayload>\nexport type IdentifierListCwtPayloadDecodedStructure = z.infer<typeof zIdentifierListCwtPayload>\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(zIdentifierListCwtPayload.in, zIdentifierListCwtPayload.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 { fetchWithLimits, hex, IdentityCommonError, isMediaType } from '@owf/identity-common'\nimport type { MdocContext } from '../../context'\nimport { IdentifierFoundInRevokedListError, InvalidRevocationListError } from '../errors'\nimport { IdentifierListCwtProtectedHeaders, MdocMediaTypes } from './identifier-list-cwt-headers'\nimport {\n type CreateIdentifierListCwtPayloadOptions,\n IdentifierListCwtClaimKey,\n IdentifierListCwtPayload,\n} from './identifier-list-cwt-payload'\n\n/** The default maximum size of an identifier list response, as of a status list response. */\nconst DEFAULT_MAX_RESPONSE_BYTES = 16 * 1024 * 1024\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, MdocMediaTypes.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 CoseValidationError (from `@owf/cose`) 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`, in a response within the `identifierList` limit of\n * `ctx.fetchLimits`, 16 MiB by default.\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 * @throws InvalidRevocationListError if the response is not an identifier list, or larger than its limit.\n */\n public static async fetch(uri: string, ctx: Pick<MdocContext, 'fetch' | 'fetchLimits'>): Promise<IdentifierListCwt> {\n let response: Response\n try {\n response = await fetchWithLimits(ctx, {\n type: 'identifierList',\n url: uri,\n accept: MdocMediaTypes.IdentifierListCwt,\n defaultMaxResponseBytes: DEFAULT_MAX_RESPONSE_BYTES,\n })\n } catch (error) {\n if (!(error instanceof IdentityCommonError)) throw error\n throw new InvalidRevocationListError(`Identifier list at ${uri}: ${error.message}`)\n }\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, MdocMediaTypes.IdentifierListCwt)) {\n throw new InvalidRevocationListError(\n `Identifier list at ${uri} was served as '${contentType}', expected '${MdocMediaTypes.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 CoseX5ChainNotBoundError,\n getIntegrityProtectedX5Chain,\n RegisteredCwtClaimKey,\n SignatureAlgorithm,\n} from '@owf/cose'\nimport { base64, base64url } from '@owf/identity-common'\nimport {\n fetchStatusList,\n JoseError,\n JoseSignatureVerificationError,\n JoseValidationError,\n type StatusList,\n StatusListCwt,\n StatusListError,\n type StatusListInfo,\n type StatusListJwtPayload,\n StatusListValidationError,\n StatusType,\n type VerifyStatusListJwtOptions,\n verifyStatusListJwt as verifyTokenStatusListJwt,\n} from '@owf/token-status-list'\nimport type { MdocContext } from '../../context'\nimport {\n InvalidIdentifierListSignatureError,\n InvalidRevocationListError,\n InvalidSignatureError,\n type MdlError,\n NoPublicKeySetOnStatusListError,\n StatusListEntryNotValidError,\n TrustedRevocationCertificatesMustContainAtleastOneCertificateError,\n UnableToExtractX5ChainFromCwtError,\n UnableToExtractX5ChainFromIdentifierListError,\n UnableToExtractX5ChainFromJwtError,\n UnprotectedX5ChainNotBoundError,\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<T>(\n verification: () => Promise<T> | T,\n /** The error to report a failed signature as. */\n invalidSignatureError: new (message: string) => MdlError\n): Promise<T> {\n try {\n return await verification()\n } catch (error) {\n if (error instanceof CoseInvalidSignatureError) throw new invalidSignatureError(error.message)\n if (error instanceof CoseX5ChainNotBoundError) throw new UnprotectedX5ChainNotBoundError(error.message)\n // The cause is what the verification callback threw, already an mdoc error\n if (error instanceof JoseSignatureVerificationError) throw error.cause ?? new invalidSignatureError(error.message)\n if (\n error instanceof StatusListError ||\n error instanceof StatusListValidationError ||\n error instanceof JoseError ||\n error instanceof JoseValidationError\n ) {\n throw new InvalidRevocationListError(error.message)\n }\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\". A status list may instead carry it in the\n * unprotected header when a protected `x5t` binds its leaf, as RFC 9360 allows.\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\n/**\n * The JWS algorithms a status list in JWT format may be signed with: ECDSA only, whose raw `r||s`\n * signature is the same in JWS and COSE, with the length of that signature (RFC 7518 § 3.4). `none`\n * and HMAC are refused, as an HMAC keyed with the public key of the certificate would be accepted\n * from anyone.\n */\ntype JwsSignatureAlgorithm = { algorithm: SignatureAlgorithm; signatureLength: number }\nconst jwsSignatureAlgorithms = new Map<string, JwsSignatureAlgorithm>([\n ['ES256', { algorithm: SignatureAlgorithm.ES256, signatureLength: 64 }],\n ['ES384', { algorithm: SignatureAlgorithm.ES384, signatureLength: 96 }],\n ['ES512', { algorithm: SignatureAlgorithm.ES512, signatureLength: 132 }],\n])\n\n/**\n * Checks the status at `idx`, only once the list verified, so that a list that does not verify is never\n * reported as a status (Token Status List § 8.3). § 12.3.6.1 accepts no status but Valid.\n */\nasync function assertStatusValid(statusList: StatusList, uri: string, idx: number) {\n const status = await asMdlRevocationListError(() => statusList.getStatus(idx), InvalidSignatureError)\n if (status !== StatusType.Valid) {\n throw new StatusListEntryNotValidError(\n `Status for id '${idx}' is not Valid (${StatusType.Valid}), but is instead '${status}'`,\n { uri, idx, status }\n )\n }\n}\n\n/**\n * Verify a status list in JWT format to the same rules as a CWT, with `verifyStatusListJwt` of\n * `@owf/token-status-list` and a callback that validates the `x5c` chain and checks the signature\n * with the `MdocContext`.\n */\nasync function verifyStatusListJwt(\n {\n jwt,\n uri,\n idx,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n skewSeconds,\n checkFreshness,\n maxDecompressedBytes,\n }: { jwt: string; uri: string; idx: number; now: Date } & Omit<\n VerifyStatusListTokenOptions,\n 'statusListInfo' | 'now'\n >,\n ctx: Pick<MdocContext, 'x509' | 'cose'>\n) {\n let chain: Array<Uint8Array> | undefined\n const verifyJwsCallback: VerifyStatusListJwtOptions['verifyJwsCallback'] = async (\n signer,\n { signingInputBytes, signature }\n ) => {\n if (signer.method !== 'x5c') throw new UnableToExtractX5ChainFromJwtError()\n // Set, as `allowedAlgorithms` only has the keys of the map\n const { algorithm, signatureLength } = jwsSignatureAlgorithms.get(signer.alg) as JwsSignatureAlgorithm\n\n const signerKey = await verifyRevocationListSigner(\n {\n // RFC 7515 § 4.1.6: standard base64 DER, not base64url.\n x5chain: signer.x5c.map((cert) => base64.decode(cert)),\n algorithm,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n },\n ctx\n )\n chain = signerKey.chain\n\n // A DER-encoded signature, as some signers produce, is not a JWS signature and is rejected here\n // rather than left to the `sign1.verify` callback, which may throw on an unexpected length.\n const signatureBytes = base64url.decode(signature)\n if (signatureBytes.length !== signatureLength) {\n throw new InvalidSignatureError(\n `The signature of the status list at ${uri} is ${signatureBytes.length} bytes, not the ${signatureLength} bytes of a raw ${signer.alg} signature`\n )\n }\n\n const verified = await ctx.cose.sign1.verify({\n toBeVerified: signingInputBytes,\n signature: signatureBytes,\n key: signerKey.key,\n algorithm,\n })\n if (!verified) throw new InvalidSignatureError(`The signature of the status list at ${uri} is not valid`)\n return { verified: true, signerJwk: signerKey.key.jwk as { kty: string } }\n }\n\n const { header, payload, statusList } = await asMdlRevocationListError(\n () =>\n verifyTokenStatusListJwt({\n jwt,\n uri,\n now,\n skewSeconds,\n checkIssuedAt: checkFreshness,\n // § 12.3.6.3: \"The exp claim shall be present.\"\n requiredClaims: ['exp'],\n allowedAlgorithms: [...jwsSignatureAlgorithms.keys()],\n verifyJwsCallback,\n maxDecompressedBytes,\n }),\n InvalidSignatureError\n )\n\n await assertStatusValid(statusList, uri, idx)\n\n return { statusListJwt: { header, payload, statusList }, chain }\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 /** The maximum size in bytes the status list may inflate to, 16 MiB by default. */\n maxDecompressedBytes?: number\n}\n\n/** A status list served in JWT format, once verified. */\nexport type VerifiedStatusListJwt = {\n header: Record<string, unknown>\n payload: StatusListJwtPayload\n statusList: StatusList\n}\n\nexport type VerifyStatusListTokenResult = {\n /** The verified list, when it was served in CWT format. */\n statusListCwt?: StatusListCwt\n /** The verified list, when it was served in JWT format instead. */\n statusListJwt?: VerifiedStatusListJwt\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 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 CWT is preferred. A list served as a JWT is still accepted as a fallback,\n * verified to the same rules; the JWS checks (ECDSA only, no `crit`, the `x5c` signer chain) live\n * in `verifyStatusListJwt`.\n *\n * The signer chain of a CWT is read from the protected header, as § 12.3.6.3 requires, or else from\n * the unprotected header when a protected `x5t` matches its leaf (RFC 9360).\n */\nexport async function verifyStatusListToken(\n {\n statusListInfo,\n trustedCertificates,\n disableCertificateChainValidation,\n now = new Date(),\n skewSeconds,\n checkFreshness,\n maxDecompressedBytes,\n }: VerifyStatusListTokenOptions,\n ctx: Pick<MdocContext, 'fetch' | 'fetchLimits' | 'x509' | 'cose' | 'crypto'>\n): Promise<VerifyStatusListTokenResult> {\n if (!disableCertificateChainValidation) assertTrustedCertificates({ trustedCertificates })\n\n const { uri, idx } = statusListInfo\n // CWT is preferred, so that an issuer that serves both returns the format § 12.3.6.3 requires. The\n // JWT is asked for with a lower quality value, and still accepted if a server returns it anyway.\n const token = await fetchStatusList({\n uri,\n customFetcher: ctx.fetch,\n fetchLimits: ctx.fetchLimits,\n acceptedFormats: ['cwt', 'jwt'],\n })\n\n // NOTE: a JWT is NOT allowed by § 12.3.6.3, but some issuers serve the status list of an mdoc\n // as JWT only. So it is accepted as a fallback, with the same checks and status handling as a CWT.\n if (typeof token === 'string') {\n const { statusListJwt, chain } = await verifyStatusListJwt(\n {\n jwt: token,\n uri,\n idx,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n skewSeconds,\n checkFreshness,\n maxDecompressedBytes,\n },\n ctx\n )\n\n return { statusListJwt, chain }\n }\n\n const statusListCwt = StatusListCwt.fromToken(token)\n\n // NOTE: an unprotected x5chain is NOT allowed by § 12.3.6.3, but RFC 9360 allows it when a\n // protected x5t binds the leaf. So it is accepted with that binding.\n const x5chain = await asMdlRevocationListError(\n () => getIntegrityProtectedX5Chain(statusListCwt, ctx.crypto),\n InvalidSignatureError\n )\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 and claims first: the token is only the issuer's if it verifies, so there is nothing\n // to read from it before that.\n await asMdlRevocationListError(\n () =>\n statusListCwt.verify(\n {\n key,\n uri,\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 const statusList = await asMdlRevocationListError(\n () => statusListCwt.payload.getStatusList({ maxDecompressedBytes }),\n InvalidSignatureError\n )\n await assertStatusValid(statusList, uri, idx)\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' | 'fetchLimits' | '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","import {\n CosePayloadMustBeDefinedError,\n cborDecode,\n DataItem,\n Sign1,\n type Sign1EncodedStructure,\n type Sign1Options,\n verifyX5t,\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 {\n defaultVerificationCallback,\n onCategoryCheck,\n type VerificationAssessmentResult,\n type VerificationCallback,\n} from '../check-callback.js'\nimport { IdentifierFoundInRevokedListError, StatusListEntryNotValidError } from '../errors.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 /**\n * Only a status list served in CWT format is returned here. One served as a JWT is verified but\n * leaves this unset; `trustedStatusListChain` is set for either when its chain was validated.\n */\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 revocation list that fails verification; succeeds silently otherwise.\n *\n * It fetches the revocation list URIs of the MSO, so call it only once the issuer is trusted: the\n * URIs of a self-signed MSO are chosen by whoever presents it. `verify` does not check the status\n * without certificate chain validation, and leaves it to this method.\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 maxStatusListDecompressedBytes,\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 /** The maximum size in bytes the status list may inflate to, 16 MiB by default. */\n maxStatusListDecompressedBytes?: number\n },\n ctx: Pick<MdocContext, 'fetch' | 'fetchLimits' | 'x509' | 'cose' | 'crypto'>\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 maxDecompressedBytes: maxStatusListDecompressedBytes,\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 /**\n * The revocation of the mdoc as data, when `error` reports one, so that a caller can tell it from\n * a revocation list that could not be verified without parsing the message.\n */\n private revocationResult(error: unknown): VerificationAssessmentResult | undefined {\n if (error instanceof StatusListEntryNotValidError) {\n const { uri, idx, status } = error\n return { type: 'statusListEntryNotValid', uri, idx, status }\n }\n\n const identifierList = this.mobileSecurityObject.status?.identifierList\n if (error instanceof IdentifierFoundInRevokedListError && identifierList) {\n return { type: 'identifierListEntryRevoked', uri: identifierList.uri, id: identifierList.id }\n }\n\n return undefined\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 /** The maximum size in bytes the status list of an mdoc may inflate to, 16 MiB by default. */\n maxStatusListDecompressedBytes?: number\n },\n ctx: Pick<MdocContext, 'x509' | 'cose' | 'fetch' | 'fetchLimits' | 'crypto'>\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 // ISO/IEC 18013-5 (second edition) § 12.3.4: an x5t, if present, shall use SHA-256. The x5chain\n // stays in the unprotected header without one, as the first edition requires.\n const x5tCheck = 'The x5t in the protected header, if present, must be SHA-256 and match the issuer certificate'\n try {\n await verifyX5t(this, this.certificate, ctx.crypto)\n onCheck({ status: 'PASSED', check: x5tCheck })\n } catch (err) {\n onCheck({ status: 'FAILED', check: x5tCheck, reason: err instanceof Error ? err.message : 'Unknown error' })\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 a trusted issuer. A forged MSO must not make the verifier request a URI of its choosing.\n // Without chain validation, the signature only shows that the MSO is signed with the key of its own\n // certificate, so the status is left to `verifyStatus` once the caller trusts the issuer.\n if (!disableStatusValidation && isSignatureValid && disableCertificateChainValidation) {\n onCheck({\n status: 'WARNING',\n check: 'Status information must be valid',\n reason:\n 'The status is not checked without certificate chain validation. Call IssuerAuth.verifyStatus once the issuer is trusted.',\n })\n } else if (!disableStatusValidation && isSignatureValid) {\n try {\n ;({ statusList, trustedStatusListChain, identifierList, trustedIdentifierListChain } = await this.verifyStatus(\n {\n now,\n skewSeconds,\n checkFreshness: true,\n trustedStatusCertificates,\n maxStatusListDecompressedBytes: options.maxStatusListDecompressedBytes,\n },\n ctx\n ))\n } catch (err) {\n // The default callback throws the reason without the check, so the reason names the lists.\n const { statusList: statusListInfo, identifierList: identifierListInfo } =\n this.mobileSecurityObject.status ?? {}\n const lists = [\n statusListInfo && `status list ${statusListInfo.uri}`,\n identifierListInfo && `identifier list ${identifierListInfo.uri}`,\n ]\n .filter(Boolean)\n .join(' and ')\n onCheck({\n status: 'FAILED',\n check: 'Status information must be valid',\n reason: `Verifying the ${lists} failed: ${err instanceof Error ? err.message : 'Unknown error'}`,\n result: this.revocationResult(err),\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 zIssuerSignedItem = typedMap([\n ['digestID', z.number()],\n ['random', zUint8Array],\n ['elementIdentifier', z.string()],\n ['elementValue', z.unknown()],\n])\n\nexport type IssuerSignedItemEncodedStructure = z.input<typeof zIssuerSignedItem>\nexport type IssuerSignedItemDecodedStructure = z.output<typeof zIssuerSignedItem>\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 zIssuerSignedItem\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 zIssuerNamespacesEncoded = z.map(z.string(), z.array(z.instanceof(DataItem)))\nexport const zIssuerNamespacesDecoded = z.map(z.string(), z.array(z.instanceof(IssuerSignedItem)))\n\nexport type IssuerNamespacesEncodedStructure = z.infer<typeof zIssuerNamespacesEncoded>\nexport type IssuerNamespacesDecodedStructure = z.infer<typeof zIssuerNamespacesDecoded>\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(zIssuerNamespacesEncoded, zIssuerNamespacesDecoded, {\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 zIssuerSigned = typedMap([\n ['nameSpaces', z.instanceof(IssuerNamespaces).exactOptional()],\n ['issuerAuth', z.instanceof(IssuerAuth)],\n])\n\nexport type IssuerSignedDecodedStructure = z.output<typeof zIssuerSigned>\nexport type IssuerSignedEncodedStructure = z.input<typeof zIssuerSigned>\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(zIssuerSigned.in, zIssuerSigned.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 /** The maximum size in bytes the status list of an mdoc may inflate to, 16 MiB by default. */\n maxStatusListDecompressedBytes?: number\n },\n ctx: Pick<MdocContext, 'x509' | 'crypto' | 'cose' | 'fetch' | 'fetchLimits'>\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","/**\n * A doc request, with the documents of the response that may answer it.\n */\nexport type DocRequestCandidates = {\n docRequestIndex: number\n uniqueDocSetRequired: boolean\n /**\n * The documents of its docType and of an issuer it accepts, which may answer it with elements left\n * out, as a holder can decline them.\n */\n candidateDocuments: Array<number>\n /**\n * The candidate documents that satisfy it.\n */\n validDocuments: Array<number>\n}\n\n/**\n * Works out which document answers which doc request, as a response does not say.\n *\n * A doc request without `uniqueDocSetRequired` is answered by every candidate document. One with it\n * is answered by one document only, and a document can answer several doc requests. A document that\n * only doc requests with `uniqueDocSetRequired` may answer therefore needs one of them to itself: when\n * there are more such documents than doc requests to take them, the response has documents too many,\n * and those doc requests fail (`excess`). They are found with a maximum matching, and are the same\n * whatever the order of the documents (the deficient part of the Dulmage-Mendelsohn decomposition).\n *\n * The other doc requests can be answered together (`canAnswer`) when the documents can be shared\n * out so that each of them with `uniqueDocSetRequired` gets one that satisfies it, while each of\n * those documents still has a doc request of its own.\n */\nexport const createAttribution = (docRequests: Array<DocRequestCandidates>) => {\n const byIndex = new Map(docRequests.map((docRequest) => [docRequest.docRequestIndex, docRequest]))\n const satisfying = new Map(\n docRequests.map((docRequest) => [docRequest.docRequestIndex, new Set(docRequest.validDocuments)])\n )\n\n // The documents that only doc requests with `uniqueDocSetRequired` may answer.\n const candidatesOf = new Map<number, Array<number>>()\n for (const { docRequestIndex, candidateDocuments } of docRequests) {\n for (const documentIndex of candidateDocuments) {\n candidatesOf.set(documentIndex, [...(candidatesOf.get(documentIndex) ?? []), docRequestIndex])\n }\n }\n const onlyUnique = Array.from(candidatesOf)\n .filter(([, docRequestIndexes]) => docRequestIndexes.every((index) => byIndex.get(index)?.uniqueDocSetRequired))\n .map(([documentIndex]) => documentIndex)\n .sort((a, b) => a - b)\n const excess = findExcess(\n onlyUnique,\n candidatesOf,\n maximumMatching(onlyUnique, (documentIndex) => candidatesOf.get(documentIndex) ?? [])\n )\n const excessDocRequests = new Set(excess.docRequestIndexes)\n const excessDocuments = new Set(excess.documentIndexes)\n const remaining = onlyUnique.filter((documentIndex) => !excessDocuments.has(documentIndex))\n\n /**\n * A doc request per remaining document, where each doc request of `required` with\n * `uniqueDocSetRequired` only takes a document that satisfies it. Undefined when there is none.\n */\n const shareOut = (required: ReadonlySet<number>) => {\n const neighbours = (documentIndex: number) =>\n // A doc request in `excess` already fails, and does not take another document.\n (candidatesOf.get(documentIndex) ?? []).filter(\n (docRequestIndex) =>\n !excessDocRequests.has(docRequestIndex) &&\n (!required.has(docRequestIndex) || (satisfying.get(docRequestIndex)?.has(documentIndex) ?? false))\n )\n const taken = maximumMatching(remaining, neighbours)\n return taken.size === remaining.length ? taken : undefined\n }\n\n /**\n * Whether the doc requests can be answered together: each satisfied by a document, and those with\n * `uniqueDocSetRequired` by a document they can have to themselves when they need one.\n */\n const answers = new Map<string, boolean>()\n const canAnswer = (docRequestIndexes: Array<number>) => {\n const required = new Set(docRequestIndexes)\n const key = Array.from(required)\n .sort((a, b) => a - b)\n .join(',')\n const known = answers.get(key)\n if (known !== undefined) return known\n const answer = canAnswerUncached(required)\n answers.set(key, answer)\n return answer\n }\n const canAnswerUncached = (required: ReadonlySet<number>) => {\n for (const docRequestIndex of required) {\n const docRequest = byIndex.get(docRequestIndex)\n if (!docRequest || docRequest.validDocuments.length === 0 || excessDocRequests.has(docRequestIndex)) return false\n }\n return shareOut(required) !== undefined\n }\n\n /**\n * Per doc request, the documents it answers when `docRequestIndexes` are answered together.\n */\n const answer = (docRequestIndexes: Array<number>) => {\n const required = new Set(docRequestIndexes)\n const taken = shareOut(required) ?? new Map<number, number>()\n const takes = new Map(Array.from(taken, ([documentIndex, docRequestIndex]) => [docRequestIndex, documentIndex]))\n\n const byDocRequest = new Map<number, Array<number>>()\n for (const docRequest of docRequests) {\n const { docRequestIndex, uniqueDocSetRequired, candidateDocuments, validDocuments } = docRequest\n if (!uniqueDocSetRequired) {\n byDocRequest.set(docRequestIndex, candidateDocuments)\n continue\n }\n if (excessDocRequests.has(docRequestIndex)) {\n byDocRequest.set(docRequestIndex, [])\n continue\n }\n // A document of its own, or else one it shares with another doc request.\n const documentIndex = takes.get(docRequestIndex) ?? validDocuments[0]\n byDocRequest.set(docRequestIndex, documentIndex === undefined ? [] : [documentIndex])\n }\n return byDocRequest\n }\n\n return { excess, canAnswer, answer }\n}\n\n/**\n * A maximum matching of `documents` to doc requests (Kuhn's algorithm), as the doc request each\n * matched document takes. O(documents · edges).\n */\nconst maximumMatching = (documents: Array<number>, neighbours: (documentIndex: number) => Array<number>) => {\n const takenBy = new Map<number, number>()\n const augment = (documentIndex: number, visited: Set<number>): boolean => {\n // A free doc request first, so that documents only move when they have to.\n const free = neighbours(documentIndex).find((docRequestIndex) => !takenBy.has(docRequestIndex))\n if (free !== undefined) {\n takenBy.set(free, documentIndex)\n return true\n }\n for (const docRequestIndex of neighbours(documentIndex)) {\n if (visited.has(docRequestIndex)) continue\n visited.add(docRequestIndex)\n const current = takenBy.get(docRequestIndex)\n if (current !== undefined && augment(current, visited)) {\n takenBy.set(docRequestIndex, documentIndex)\n return true\n }\n }\n return false\n }\n for (const documentIndex of documents) augment(documentIndex, new Set())\n\n return new Map(Array.from(takenBy, ([docRequestIndex, documentIndex]) => [documentIndex, docRequestIndex]))\n}\n\n/**\n * The documents left without a doc request in a maximum matching, with every document an alternating\n * path reaches from them: along a candidate of a document, and back along the document that doc\n * request takes. These are the documents some maximum matching leaves without a doc request, and\n * their candidates are the doc requests with documents too many.\n */\nconst findExcess = (\n documents: Array<number>,\n candidatesOf: Map<number, Array<number>>,\n matching: Map<number, number>\n) => {\n const takes = new Map(Array.from(matching, ([documentIndex, docRequestIndex]) => [docRequestIndex, documentIndex]))\n\n const queue = documents.filter((documentIndex) => !matching.has(documentIndex))\n const reached = new Set(queue)\n for (let position = 0; position < queue.length; position++) {\n for (const docRequestIndex of candidatesOf.get(queue[position] as number) ?? []) {\n const next = takes.get(docRequestIndex)\n if (next !== undefined && !reached.has(next)) {\n reached.add(next)\n queue.push(next)\n }\n }\n }\n\n const documentIndexes = Array.from(reached).sort((a, b) => a - b)\n const docRequestIndexes = new Set(documentIndexes.flatMap((documentIndex) => candidatesOf.get(documentIndex) ?? []))\n return { documentIndexes, docRequestIndexes: Array.from(docRequestIndexes).sort((a, b) => a - b) }\n}\n","import { hexEncode } from '@owf/identity-common'\nimport { parseCertificate } from '@owf/x509'\nimport type { VerificationCallback } from '../mdoc/check-callback'\nimport { InvalidDeviceRequestMatchOptionsError } from '../mdoc/errors'\nimport type { AlternativeDataElementsSet } from '../mdoc/models/alternative-data-elements-set'\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 {\n describeAgeOverLimitViolations,\n findAgeOverCandidate,\n findAgeOverLimitViolations,\n findAgeOverRequestLimitViolations,\n} from './ageOver'\nimport { createAttribution } from './attribution'\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 and no use cases does not say whether it asks\n * for all of them, or for any one of them. ISO/IEC TS 23220-4 7.2.1.3.2 reads it as all of them,\n * which is the default: a single mandatory use case whose document set holds every doc request.\n * Set this to treat them as alternatives instead, one optional use case per doc request, of which\n * at least one has to be satisfied. That is how the iOS DC API presents such a request.\n *\n * A device request that carries use cases (ISO/IEC TS 23220-4 7.2.1.3.4, taken up by the second\n * edition of 18013-5) is matched by them, and this option does not apply. Neither does it to a\n * 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 * Set when the doc request has alternatives for the element (ISO/IEC TS 23220-4 7.2.1.3.2): every\n * way it can be answered, in order of preference. The element itself comes first when it is\n * there, then each alternative set whose elements all are, in the reader's order, possibly in other\n * namespaces (18013-5 second edition 10.2.4).\n *\n * `disclosedElementIdentifier`, `elementValue` and `source` describe the first element of the first\n * option. That option is an alternative set (it has an `alternativeElementSetIndex`) only when the\n * element itself is not there. A holder discloses an alternative set by choosing it with the\n * `alternatives` of the document it creates, and otherwise the element itself.\n */\n options?: NonEmptyArray<ClaimMatchOption>\n}\n\n/**\n * One way to answer a requested element that has alternatives (ISO/IEC TS 23220-4 7.2.1.3.2): the\n * element itself, or every element of one of its alternative sets (18013-5 second edition 10.2.4).\n */\nexport type ClaimMatchOption = {\n /**\n * Index into the `alternativeElementSets` of the element, when the option is one of them rather\n * than the element itself.\n */\n alternativeElementSetIndex?: number\n elements: NonEmptyArray<DisclosedElement>\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\nexport type IssuerMatchSuccess = { success: true }\nexport type IssuerMatchFailure = { success: false; reason: string }\n\n/**\n * Whether a document or credential comes from an issuer the doc request accepts: a certificate in\n * its certificate chain has one of the `issuerIdentifiers` of the `requestInfo` of the doc request\n * as its authority key identifier (ISO/IEC TS 23220-4 7.2.1.3.2, 18013-5 second edition 10.2.4).\n * Only present when the doc request names issuers.\n */\nexport type IssuerMatchResult = IssuerMatchSuccess | IssuerMatchFailure\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 issuer?: IssuerMatchSuccess\n claims: DocumentClaimsMatchSuccess\n}\n\nexport type DocumentMatchFailure = DocumentMatchBase & {\n success: false\n docType: DocTypeMatchResult\n issuer?: IssuerMatchResult\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 /**\n * Empty, unless the doc request requires a unique document set that the response does not give,\n * see `reason`.\n */\n validDocuments: Array<DocumentMatchSuccess>\n /**\n * Set when the `requestInfo` of the doc request sets `uniqueDocSetRequired` (ISO/IEC TS 23220-4\n * 7.2.1.3.2), and the response has more documents for it than one: documents of its docType and\n * of an issuer it accepts, satisfying it or not, that may only answer doc requests that take one\n * document each, this one among them, and outnumber them; or when such documents leave it none\n * that satisfies it. See {@link DeviceRequestAttribution}.\n */\n reason?: string\n}\n\nexport type DocRequestMatch = DocRequestMatchSuccess | DocRequestMatchFailure\n\n/**\n * How a use case is satisfied.\n */\nexport type UseCaseMatch = {\n /**\n * Index into `useCases` of the use case this result is about, which for use cases of the device\n * request is also their index into `deviceRequestInfo.useCases`.\n */\n useCaseIndex: number\n mandatory: boolean\n /**\n * The purpose hints of the use case, to tell the user what each use case is for (18013-5 second\n * edition 10.2.5). Only use cases of the `deviceRequestInfo` have them.\n */\n purposeHints?: Map<string, number>\n /**\n * Whether the use case can be answered on its own. Whether it can be answered together with the\n * others is in `attribution` of the match.\n */\n success: boolean\n /**\n * Every document set of the use case, in request order: the doc requests, by index, that answer\n * it together.\n */\n documentSets: Array<Array<number>>\n /**\n * The document sets of `documentSets` whose doc requests are all satisfied, in request order.\n * Empty when none is. A holder answers exactly one of them (ISO/IEC TS 23220-4 7.2.1.4).\n */\n matchingDocumentSets: Array<Array<number>>\n}\n\n/**\n * Where the use cases of a match come from.\n *\n * `'deviceRequestInfo'`: the use cases of the `deviceRequestInfo` of the device request (ISO/IEC TS\n * 23220-4 7.2.1.3.4).\n *\n * `'allDocRequests'`: the device request carries none, so every doc request is requested (7.2.1.3.2):\n * a single mandatory use case, whose one document set holds every doc request.\n *\n * `'eachDocRequest'`: the device request carries none, and\n * `treatAmbiguousMultipleDocRequestsAsAlternatives` is set: one optional use case per doc request.\n */\nexport type UseCasesSource = 'deviceRequestInfo' | 'allDocRequests' | 'eachDocRequest'\n\nexport type UseCasesMatch = {\n useCasesSource: UseCasesSource\n /**\n * One entry per use case, in order. The match succeeds when every mandatory use case is satisfied\n * and at least one use case is (18013-5 second edition 10.2.5).\n */\n useCases: Array<UseCaseMatch>\n}\n\n/**\n * Which document answers which doc request, and with which document set each use case is answered.\n * A response does not say, so the match works it out. A document may answer every doc request of\n * its docType and of an issuer it accepts, also with elements left out, as a holder can decline\n * them, and one document can answer several doc requests. A doc request with `uniqueDocSetRequired`\n * takes one document only, so a document that only such doc requests may answer needs one of them\n * to itself, and they are only satisfied together when that leaves each of them a document that\n * satisfies it. Whether they are does not depend on the order of the documents; which document a\n * doc request takes, when several would do, may.\n *\n * A holder answers each use case with exactly one document set (ISO/IEC TS 23220-4 7.2.1.4), so a\n * document that answers no doc request of the sets in `useCases`, nor of a use case that is not\n * satisfied, should not have been sent, which `reportDeviceRequestMatch` warns about.\n */\nexport type DeviceRequestAttribution = {\n /**\n * The use cases the response is taken to answer, in order, each with its document set: every\n * mandatory use case, and the others that can be answered together with them, tried in order. Of\n * the `matchingDocumentSets` of a use case, the set the most documents may answer is tried first,\n * then request order.\n */\n useCases: Array<{ useCaseIndex: number; documentSet: Array<number> }>\n /**\n * Per document, in response order, the doc requests it answers, in order. Empty for a document\n * that answers none.\n */\n documents: Array<{ documentIndex: number; docRequestIndexes: Array<number> }>\n}\n\ntype DeviceRequestMatchBase = UseCasesMatch & {\n /**\n * Documents in the response whose docType no doc request asked for.\n */\n unrequestedDocuments: Array<{ documentIndex: number; docType: DocType }>\n attribution: DeviceRequestAttribution\n}\n\n/**\n * Every mandatory use case is satisfied, and at least one use case is.\n */\nexport type DeviceRequestMatchSuccess = DeviceRequestMatchBase &\n (\n | {\n success: true\n useCasesSource: 'allDocRequests'\n /**\n * One entry per doc request, in request order. All of them are successful.\n */\n docRequests: Array<DocRequestMatchSuccess>\n }\n | {\n success: true\n useCasesSource: 'deviceRequestInfo' | 'eachDocRequest'\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<DocRequestMatch>\n }\n )\n\nexport type DeviceRequestMatchFailure = DeviceRequestMatchBase & {\n success: false\n /**\n * Set when every use case the response has to satisfy can be satisfied on its own, or every doc\n * request when they are all requested, but not together, see {@link DeviceRequestAttribution}.\n */\n reason?: string\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 issuer?: IssuerMatchSuccess\n claims: ClaimsMatchSuccess\n}\n\nexport type CredentialMatchFailure = CredentialMatchBase & {\n success: false\n docType: DocTypeMatchResult\n issuer?: IssuerMatchResult\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 mandatory use case can be satisfied, and at least one use case can.\n */\nexport type HolderDeviceRequestMatchSuccess = UseCasesMatch &\n (\n | {\n success: true\n useCasesSource: 'allDocRequests'\n /**\n * One entry per doc request, in request order. All of them are successful.\n */\n docRequests: Array<HolderDocRequestMatchSuccess>\n }\n | {\n success: true\n useCasesSource: 'deviceRequestInfo' | 'eachDocRequest'\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<HolderDocRequestMatch>\n }\n )\n\nexport type HolderDeviceRequestMatchFailure = UseCasesMatch & {\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 * The doc requests are matched by use case: those of the device request (ISO/IEC TS 23220-4\n * 7.2.1.3.4) when it carries them, and otherwise every doc request as one mandatory use case, or each\n * doc request as an optional one when `treatAmbiguousMultipleDocRequestsAsAlternatives` is set in\n * `matchOptions`. The match succeeds when every mandatory use case is satisfied and at least one is.\n *\n * The `requestInfo` of a doc request is applied too: a document of an issuer it does not name\n * fails, an alternative set it allows answers a requested element, and its elements count as\n * requested rather than over-disclosed, and with\n * `uniqueDocSetRequired` the doc request fails when the response has more documents for it than\n * one, see {@link DeviceRequestAttribution} for which document answers which doc request.\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 /**\n * Per document, in response order, its certificate chain as validated against the trusted\n * certificates, leaf first. The `issuerIdentifiers` of a doc request are matched against it, and\n * a document without one does not satisfy a doc request that names issuers. The x5chain is not\n * used: it is in the unprotected header of the IssuerAuth, so a holder can add the certificate of\n * any issuer to it. `Verifier.verifyDeviceResponse` passes the chains it validates.\n */\n issuerCertificateChains?: Array<Array<Uint8Array> | undefined>\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 matches = deviceRequest.docRequests.map((docRequest, docRequestIndex) => {\n const { docType, namespaces, requestInfo } = 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 issuerResult = matchIssuer(\n requestInfo?.issuerIdentifiers,\n options.issuerCertificateChains?.[documentIndex],\n 'validated certificate chain'\n )\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 alternatives: requestInfo?.alternativeDataElements,\n })\n const claimsResult: DocumentClaimsMatchResult = {\n ...toClaimsMatchResult(claims),\n unrequestedClaims: unusedElements,\n }\n\n const issuer = issuerResult ? { issuer: issuerResult } : {}\n return docTypeResult.success && claimsResult.success && issuerResult?.success !== false\n ? {\n documentIndex,\n success: true,\n docType: docTypeResult,\n ...(issuer as { issuer?: IssuerMatchSuccess }),\n claims: claimsResult,\n }\n : { documentIndex, success: false, docType: docTypeResult, ...issuer, claims: claimsResult }\n })\n\n return {\n docRequestIndex,\n docType,\n uniqueDocSetRequired: requestInfo?.uniqueDocSetRequired ?? false,\n // A document of its docType and of an issuer it accepts may answer it with elements left out.\n candidateDocuments: documentMatches.filter(\n (documentMatch) => documentMatch.docType.success && documentMatch.issuer?.success !== false\n ),\n validDocuments: documentMatches.filter((documentMatch) => documentMatch.success),\n failedDocuments: documentMatches.filter((documentMatch) => !documentMatch.success),\n }\n })\n\n const attribution = createAttribution(\n matches.map(({ docRequestIndex, uniqueDocSetRequired, candidateDocuments, validDocuments }) => ({\n docRequestIndex,\n uniqueDocSetRequired,\n candidateDocuments: candidateDocuments.map((document) => document.documentIndex),\n validDocuments: validDocuments.map((document) => document.documentIndex),\n }))\n )\n const excessDocuments = new Set(attribution.excess.documentIndexes)\n\n const docRequests = matches.map(({ uniqueDocSetRequired, candidateDocuments, ...match }): DocRequestMatch => {\n const { docRequestIndex, docType, validDocuments, failedDocuments } = match\n const failure = (reason: string): DocRequestMatchFailure => ({\n docRequestIndex,\n docType,\n success: false,\n validDocuments,\n failedDocuments,\n reason,\n })\n\n // More documents than doc requests that take one document each can take, this one among them.\n const excess = uniqueDocSetRequired\n ? candidateDocuments\n .map((document) => document.documentIndex)\n .filter((documentIndex) => excessDocuments.has(documentIndex))\n : []\n if (excess.length > 0) {\n const own = new Set(excess)\n const others = matches\n .filter((other) => other.candidateDocuments.some((document) => own.has(document.documentIndex)))\n .map((other) => other.docRequestIndex)\n return failure(\n `Doc request ${docRequestIndex} requires a unique document set, but the response has more documents than such doc requests can take: documents ${excess.join(', ')} may only answer ${others.length === 1 ? `doc request ${docRequestIndex}` : `doc requests ${others.join(', ')}, which all do`}`\n )\n }\n if (uniqueDocSetRequired && isNonEmptyArray(validDocuments) && !attribution.canAnswer([docRequestIndex])) {\n return failure(\n `Doc request ${docRequestIndex} requires a unique document set, and the documents that only doc requests like it may answer leave it none of documents ${validDocuments.map((document) => document.documentIndex).join(', ')}, which satisfy it`\n )\n }\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 const useCases = matchUseCases(\n resolveUseCases(deviceRequest, matchOptions?.treatAmbiguousMultipleDocRequestsAsAlternatives),\n docRequests,\n attribution.canAnswer\n )\n\n // Which document set each use case is answered with: of a use case, the set the most documents\n // may answer is tried first.\n const documentsOf = (documentSet: Array<number>) =>\n new Set(\n documentSet.flatMap((index) => matches[index]?.candidateDocuments.map((document) => document.documentIndex) ?? [])\n ).size\n const chosen = useCases.success\n ? chooseDocumentSets(useCases.match.useCases, attribution.canAnswer, documentsOf)\n : undefined\n const byDocRequest = attribution.answer((chosen ?? []).flatMap(({ documentSet }) => documentSet))\n const docRequestsOf = documents.map((): Array<number> => [])\n for (const [docRequestIndex, documentIndexes] of Array.from(byDocRequest).sort(([a], [b]) => a - b)) {\n for (const documentIndex of documentIndexes) docRequestsOf[documentIndex]?.push(docRequestIndex)\n }\n const answered = {\n useCases: chosen ?? [],\n documents: docRequestsOf.map((docRequestIndexes, documentIndex) => ({ documentIndex, docRequestIndexes })),\n }\n\n if (!useCases.success || !chosen) {\n // Use cases or doc requests that can each be answered, but not together, fail no check of their own.\n const reason = useCases.success\n ? 'Every use case it requires can be answered, but not together: the doc requests with uniqueDocSetRequired among them cannot each have a document that satisfies them'\n : useCases.match.useCasesSource === 'allDocRequests' && docRequests.every(isSuccess)\n ? 'Its doc requests are each satisfied, but not together: those with uniqueDocSetRequired cannot each have a document that satisfies them'\n : undefined\n return {\n success: false,\n ...useCases.match,\n docRequests,\n unrequestedDocuments,\n attribution: answered,\n ...(reason ? { reason } : {}),\n }\n }\n if (useCases.match.useCasesSource !== 'allDocRequests') {\n return {\n success: true,\n useCasesSource: useCases.match.useCasesSource,\n useCases: useCases.match.useCases,\n docRequests,\n unrequestedDocuments,\n attribution: answered,\n }\n }\n // A single use case holding every doc request is only satisfied when all of them are.\n return {\n success: true,\n useCasesSource: 'allDocRequests',\n useCases: useCases.match.useCases,\n docRequests: docRequests.filter(isSuccess),\n unrequestedDocuments,\n attribution: answered,\n }\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 * The doc requests are matched by use case, the same way as {@link matchDeviceRequest} does, and each\n * use case lists the document sets the credentials can answer (`matchingDocumentSets`), of which\n * the holder picks one.\n *\n * The `requestInfo` of a doc request is applied too: a credential of an issuer it does not name\n * fails, and a requested element is answered by one of its alternative sets when the credential\n * has one. The claims list every option, of which the holder can pick another than the first.\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, requestInfo } = 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 issuerResult = matchIssuer(\n requestInfo?.issuerIdentifiers,\n issuerAuthCertificateChain(issuerSigned),\n 'x5chain of the IssuerAuth'\n )\n\n const claimsResult = toClaimsMatchResult(\n matchElements({\n mode: 'holder',\n namespaces,\n issuerSigned,\n keyAuthorizations: mobileSecurityObject.deviceKeyInfo.keyAuthorizations,\n deviceNamespaces,\n alternatives: requestInfo?.alternativeDataElements,\n }).claims\n )\n\n const issuer = issuerResult ? { issuer: issuerResult } : {}\n return docTypeResult.success && claimsResult.success && issuerResult?.success !== false\n ? {\n credentialIndex,\n success: true,\n docType: docTypeResult,\n ...(issuer as { issuer?: IssuerMatchSuccess }),\n claims: claimsResult,\n }\n : { credentialIndex, success: false, docType: docTypeResult, ...issuer, 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 const useCases = matchUseCases(\n resolveUseCases(deviceRequest, options.treatAmbiguousMultipleDocRequestsAsAlternatives),\n docRequests\n )\n if (!useCases.success) return { success: false, ...useCases.match, docRequests }\n if (useCases.match.useCasesSource !== 'allDocRequests') {\n return {\n success: true,\n useCasesSource: useCases.match.useCasesSource,\n useCases: useCases.match.useCases,\n docRequests,\n }\n }\n // A single use case holding every doc request is only satisfied when all of them are.\n return {\n success: true,\n useCasesSource: 'allDocRequests',\n useCases: useCases.match.useCases,\n docRequests: docRequests.filter(isSuccess),\n }\n}\n\ntype ResolvedUseCases = {\n useCasesSource: UseCasesSource\n useCases: Array<{ mandatory: boolean; purposeHints?: Map<string, number>; documentSets: Array<Array<number>> }>\n}\n\n/**\n * The use cases to match the device request by: its own (ISO/IEC TS 23220-4 7.2.1.3.4), and\n * otherwise every doc request as one mandatory use case (7.2.1.3.2), or with\n * `treatAmbiguousMultipleDocRequestsAsAlternatives` each doc request as an optional use case. A\n * single doc request is not ambiguous, so it always is a mandatory use case of its own.\n */\nconst resolveUseCases = (\n deviceRequest: DeviceRequest,\n treatAmbiguousMultipleDocRequestsAsAlternatives = false\n): ResolvedUseCases => {\n const useCases = deviceRequest.deviceRequestInfo?.useCases\n if (useCases) {\n return {\n useCasesSource: 'deviceRequestInfo',\n useCases: useCases.map(({ mandatory, purposeHints, documentSets }) => ({\n mandatory,\n ...(purposeHints ? { purposeHints } : {}),\n documentSets,\n })),\n }\n }\n\n const docRequestIndexes = deviceRequest.docRequests.map((_, docRequestIndex) => docRequestIndex)\n if (treatAmbiguousMultipleDocRequestsAsAlternatives && docRequestIndexes.length > 1) {\n return {\n useCasesSource: 'eachDocRequest',\n useCases: docRequestIndexes.map((docRequestIndex) => ({ mandatory: false, documentSets: [[docRequestIndex]] })),\n }\n }\n\n return { useCasesSource: 'allDocRequests', useCases: [{ mandatory: true, documentSets: [docRequestIndexes] }] }\n}\n\n/**\n * Per use case the document sets whose doc requests are all satisfied, and whether the device\n * request is: every mandatory use case and at least one use case has to be (18013-5 second edition\n * 10.2.5).\n */\nconst matchUseCases = (\n { useCasesSource, useCases }: ResolvedUseCases,\n docRequests: Array<{ success: boolean }>,\n // Whether the doc requests of a set can be answered together, see `createAttribution`.\n canAnswer: (docRequestIndexes: Array<number>) => boolean = () => true\n) => {\n const matches = useCases.map(({ mandatory, purposeHints, documentSets }, useCaseIndex): UseCaseMatch => {\n const satisfied = documentSets.filter(\n (set) => set.every((index) => docRequests[index]?.success === true) && canAnswer(set)\n )\n return {\n useCaseIndex,\n mandatory,\n ...(purposeHints ? { purposeHints } : {}),\n success: satisfied.length > 0,\n documentSets,\n matchingDocumentSets: satisfied,\n }\n })\n\n return {\n match: { useCasesSource, useCases: matches },\n success:\n matches.every((useCase) => !useCase.mandatory || useCase.success) && matches.some((useCase) => useCase.success),\n }\n}\n\n/**\n * One document set per use case, answered together: every mandatory use case, and as many others as\n * can be added in order. The sets of a use case are tried the one `documentsOf` gives most first,\n * then in request order. Undefined when the mandatory use cases cannot be answered together, or\n * without one, when none can be answered. Tries every combination of the sets of the mandatory use\n * cases, which the request sets.\n */\nconst chooseDocumentSets = (\n useCases: Array<UseCaseMatch>,\n canAnswer: (docRequestIndexes: Array<number>) => boolean,\n documentsOf: (documentSet: Array<number>) => number\n): Array<{ useCaseIndex: number; documentSet: Array<number> }> | undefined => {\n const preferences = new Map(\n useCases.map((useCase) => [\n useCase.useCaseIndex,\n useCase.matchingDocumentSets\n .map((documentSet, order) => ({ documentSet, order, documents: documentsOf(documentSet) }))\n .sort((a, b) => b.documents - a.documents || a.order - b.order)\n .map(({ documentSet }) => ({ useCaseIndex: useCase.useCaseIndex, documentSet })),\n ])\n )\n const preferred = (useCase: UseCaseMatch) => preferences.get(useCase.useCaseIndex) ?? []\n\n const mandatory = useCases.filter((useCase) => useCase.mandatory)\n const search = (\n index: number,\n chosen: Array<{ useCaseIndex: number; documentSet: Array<number> }>\n ): typeof chosen | undefined => {\n const useCase = mandatory[index]\n if (!useCase) return chosen\n for (const option of preferred(useCase)) {\n const next = [...chosen, option]\n if (!canAnswer(next.flatMap(({ documentSet }) => documentSet))) continue\n const found = search(index + 1, next)\n if (found) return found\n }\n return undefined\n }\n\n const chosen = search(0, [])\n if (!chosen) return undefined\n for (const useCase of useCases) {\n if (useCase.mandatory) continue\n const option = preferred(useCase).find(({ documentSet }) =>\n canAnswer([...chosen.flatMap((answered) => answered.documentSet), ...documentSet])\n )\n if (option) chosen.push(option)\n }\n chosen.sort((a, b) => a.useCaseIndex - b.useCaseIndex)\n return chosen.length > 0 ? chosen : undefined\n}\n\n/**\n * Whether a document or credential comes from one of `issuerIdentifiers`; undefined when the doc\n * request names no issuer. Matched against the authority key identifiers of `certificateChain`:\n * for a verifier the chain it validated, as the x5chain is in the unprotected header of the\n * IssuerAuth, and for a holder the x5chain of its own credential. Without a chain, it fails.\n *\n * @internal\n */\nexport const matchIssuer = (\n issuerIdentifiers: Array<Uint8Array> | undefined,\n certificateChain: Array<Uint8Array> | undefined,\n chainName: 'validated certificate chain' | 'x5chain of the IssuerAuth'\n): IssuerMatchResult | undefined => {\n if (!issuerIdentifiers) return undefined\n\n const accepted = `the ${issuerIdentifiers.length} issuer identifier(s) the doc request accepts`\n if (!certificateChain) {\n return { success: false, reason: `The document has no ${chainName} to match ${accepted} against` }\n }\n\n const keyIdentifiers = certificateChain.flatMap((certificate) => {\n try {\n return parseCertificate(certificate).authorityKeyIdentifier ?? []\n } catch {\n // A certificate that does not parse has no key identifier to match.\n return []\n }\n })\n\n return issuerIdentifiers.some((identifier) => keyIdentifiers.includes(hexEncode(identifier)))\n ? { success: true }\n : {\n success: false,\n reason: `No certificate in the ${chainName} has one of ${accepted} as its authority key identifier`,\n }\n}\n\n/**\n * The x5chain of the IssuerAuth of a credential, which a holder matches issuers against; undefined\n * when it cannot be read.\n *\n * @internal\n */\nexport const issuerAuthCertificateChain = (issuerSigned: IssuerSigned) => {\n try {\n return issuerSigned.issuerAuth.certificateChain\n } catch {\n return undefined\n }\n}\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 /**\n * The first element of the first option, see `claim.options`.\n */\n element: ElementCandidate\n /**\n * Every option, as `claim.options` lists them, when the element has alternatives.\n */\n options?: NonEmptyArray<ElementOption>\n }\n | { claim: ClaimMatchFailure; element?: undefined; options?: undefined }\n\n/**\n * @internal\n */\nexport type ElementOption = { alternativeElementSetIndex?: number; elements: NonEmptyArray<ElementCandidate> }\n\nconst toDisclosedElement = ({ issuerSignedItem: _, ...element }: ElementCandidate): DisclosedElement => element\n\nconst groupByNamespace = (elements: Array<DisclosedElement>) => {\n const namespaces = new Map<Namespace, Array<DataElementIdentifier>>()\n for (const { namespace, elementIdentifier } of elements) {\n namespaces.set(namespace, [...(namespaces.get(namespace) ?? []), elementIdentifier])\n }\n return namespaces\n}\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 /**\n * The alternative data elements of the `requestInfo` of the doc request (ISO/IEC TS 23220-4\n * 7.2.1.3.2). Each alternative set whose elements all are there (18013-5 second edition 10.2.4),\n * each found the way the requested element would be, is an option to answer the requested element,\n * after the element itself. The first option answers it. For a holder, an alternative set that\n * would make the response disclose more than two age_over_NN elements in a namespace is not an\n * option.\n */\n alternatives?: Array<AlternativeDataElementsSet>\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 inNamespace = (namespace: Namespace, source: DisclosedElementSource) =>\n available.filter((element) => element.namespace === namespace && element.source === source)\n const authorizedDeviceSigned = (namespace: Namespace) =>\n inNamespace(namespace, 'deviceSigned').filter((element) =>\n isDeviceSignedElementAuthorized(keyAuthorizations, element)\n )\n\n /**\n * The element that answers a request for `elementIdentifier` in `namespace`: for a holder\n * issuer-signed, else device-signed when authorized and given for exactly that element; for a\n * verifier from the source its options allow. The same rules as for a requested element.\n */\n const lookup = (namespace: Namespace, elementIdentifier: DataElementIdentifier): ElementCandidate | undefined => {\n if (mode === 'holder') {\n return (\n findElement(elementIdentifier, inNamespace(namespace, 'issuerSigned')) ??\n authorizedDeviceSigned(namespace).find((candidate) => candidate.elementIdentifier === elementIdentifier)\n )\n }\n const namespaceOptions = getOwnProperty(options.elements, namespace)\n const { source = 'issuerSigned' } =\n getOwnProperty(namespaceOptions, elementIdentifier) ?? getOwnProperty(namespaceOptions, '*') ?? {}\n return source === 'deviceSigned'\n ? findElement(elementIdentifier, authorizedDeviceSigned(namespace))\n : (findElement(elementIdentifier, inNamespace(namespace, 'issuerSigned')) ??\n (source === 'any' ? findElement(elementIdentifier, authorizedDeviceSigned(namespace)) : undefined))\n }\n\n /**\n * Every alternative set of the requested element whose elements all are there, in the reader's\n * order; undefined when the doc request has no alternatives for the element.\n */\n const findAlternatives = (namespace: Namespace, elementIdentifier: DataElementIdentifier) => {\n const alternative = options.alternatives?.find(\n ({ requestedElement: [requestedNamespace, requestedIdentifier] }) =>\n requestedNamespace === namespace && requestedIdentifier === elementIdentifier\n )\n if (!alternative) return undefined\n\n return alternative.alternativeElementSets.flatMap((set, alternativeElementSetIndex): Array<ElementOption> => {\n const elements = set.map(([alternativeNamespace, alternativeIdentifier]) =>\n lookup(alternativeNamespace, alternativeIdentifier)\n )\n return elements.every((element) => element !== undefined) && isNonEmptyArray(elements)\n ? [{ alternativeElementSetIndex, elements }]\n : []\n })\n }\n\n /** The options to answer a requested element: itself when it is there, then its alternatives. */\n const optionsFor = (\n namespace: Namespace,\n elementIdentifier: DataElementIdentifier,\n element: ElementCandidate | undefined\n ) => {\n const alternatives = findAlternatives(namespace, elementIdentifier)\n const elementOptions: Array<ElementOption> = [\n ...(element ? [{ elements: [element] as NonEmptyArray<ElementCandidate> }] : []),\n ...(alternatives ?? []),\n ]\n return {\n options: isNonEmptyArray(elementOptions) ? elementOptions : undefined,\n hasAlternatives: alternatives !== undefined,\n }\n }\n\n const claims: Array<ElementMatch> = []\n const usedElements = new Set<DisclosedElement>()\n // Holder claims are only settled once every requested element is looked up, see below.\n const holderClaims: Array<{\n claim: ClaimMatchBase\n element: ElementCandidate | undefined\n elementOptions: Array<ElementOption> | undefined\n hasAlternatives: boolean\n }> = []\n\n /**\n * The claim is answered by the first option. `listOptions` is set when the element has\n * alternatives, so that every option is reported.\n */\n const success = (claim: ClaimMatchBase, elementOptions: NonEmptyArray<ElementOption>, listOptions: boolean) => {\n const [first] = elementOptions\n for (const element of first.elements) usedElements.add(element)\n const [element] = first.elements\n\n claims.push({\n element,\n ...(listOptions ? { options: elementOptions } : {}),\n claim: {\n ...claim,\n success: true,\n disclosedElementIdentifier: element.elementIdentifier,\n elementValue: element.elementValue,\n source: element.source,\n ...(listOptions\n ? {\n options: elementOptions.map(({ alternativeElementSetIndex, elements }) => ({\n ...(alternativeElementSetIndex === undefined ? {} : { alternativeElementSetIndex }),\n elements: elements.map(toDisclosedElement) as NonEmptyArray<DisclosedElement>,\n })) as NonEmptyArray<ClaimMatchOption>,\n }\n : {}),\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 const { options: elementOptions, hasAlternatives } = optionsFor(namespace, elementIdentifier, element)\n holderClaims.push({ claim, element, elementOptions, hasAlternatives })\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 // ISO/IEC TS 23220-4 7.2.1.3.2: an alternative set the request allows answers it too, when every\n // element of it is there (18013-5 second edition 10.2.4).\n const { options: elementOptions, hasAlternatives } = optionsFor(namespace, elementIdentifier, element)\n if (elementOptions) {\n success(claim, elementOptions, hasAlternatives)\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 // 18013-5 7.2.5: at most two age_over_NN elements are disclosed per namespace. The requested\n // elements the credential has are disclosed by default, so an alternative set is only offered when,\n // disclosed with those of the other claims, it keeps every namespace within two.\n for (const [claimIndex, { claim, element, elementOptions, hasAlternatives }] of holderClaims.entries()) {\n const others = holderClaims.flatMap((other, otherIndex) =>\n otherIndex !== claimIndex && other.element ? [other.element] : []\n )\n const options = elementOptions?.filter(\n (option) =>\n option.alternativeElementSetIndex === undefined ||\n findAgeOverLimitViolations(groupByNamespace([...others, ...option.elements])).length === 0\n )\n if (options && isNonEmptyArray(options)) {\n success(claim, options, hasAlternatives)\n continue\n }\n\n const { namespace, elementIdentifier } = claim\n failure(claim, {\n failure: 'notDisclosed',\n reason:\n elementOptions && !element\n ? `Element '${elementIdentifier}' in namespace '${namespace}' is not in the credential, and each of its alternative sets the credential has would disclose more than two age_over_NN elements in a namespace`\n : 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 }\n\n // An element of an alternative set of a requested element is requested too, whether or not it\n // answers it, so disclosing it is not over-disclosure.\n for (const { requestedElement, alternativeElementSets } of options.alternatives ?? []) {\n if (!namespaces.get(requestedElement[0])?.has(requestedElement[1])) continue\n for (const [alternativeNamespace, alternativeIdentifier] of alternativeElementSets.flat()) {\n const element = lookup(alternativeNamespace, alternativeIdentifier)\n if (element) usedElements.add(element)\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\nconst isSuccess = <T extends { success: boolean }>(result: T): result is Extract<T, { success: true }> => result.success\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, and when the\n * device request carries use cases, one check per mandatory use case and one for \"at least one\".\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 // Doc requests that are each satisfied may still not be answered together, see `createAttribution`.\n const failureReasons = (documentSets: Array<Array<number>>) => {\n const docRequestIndexes = documentSets.flat()\n const reasons = match.docRequests\n .filter((docRequest) => !docRequest.success && docRequestIndexes.includes(docRequest.docRequestIndex))\n .map((docRequest) => `Doc request ${docRequest.docRequestIndex}: ${docRequestFailureReason(docRequest)}`)\n const satisfied = new Set(match.docRequests.filter(isSuccess).map((docRequest) => docRequest.docRequestIndex))\n const notTogether = documentSets.filter((set) => set.every((index) => satisfied.has(index)))\n if (notTogether.length > 0) {\n reasons.push(\n `Doc requests ${notTogether.map((set) => set.join(', ')).join('; ')} are each satisfied, but not together: those with uniqueDocSetRequired cannot each have a document that satisfies them`\n )\n }\n return reasons.join('. ')\n }\n\n if (match.useCasesSource === 'deviceRequestInfo') {\n // A mandatory use case is a check of its own; an optional one only counts towards \"at least one\".\n for (const useCase of match.useCases) {\n if (!useCase.mandatory) continue\n const check = `Device response must satisfy mandatory use case ${useCase.useCaseIndex}`\n if (useCase.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: `None of the document sets of use case ${useCase.useCaseIndex} is satisfied. ${failureReasons(useCase.documentSets)}`,\n result,\n })\n }\n }\n\n const check = 'Device response must satisfy at least one use case'\n if (match.useCases.some((useCase) => useCase.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: `No use case is satisfied. ${failureReasons(match.useCases.flatMap((useCase) => useCase.documentSets))}`,\n result,\n })\n }\n } else if (match.useCasesSource === 'eachDocRequest') {\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 if (!match.success && match.reason) {\n onCheck({\n status: 'FAILED',\n check: 'Device response must answer the doc requests it satisfies together',\n category: 'DOCUMENT_FORMAT',\n reason: match.reason,\n result,\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 // A holder answers each use case with exactly one document set (ISO/IEC TS 23220-4 7.2.1.4). A\n // document that may answer a doc request of a use case the response is not taken to answer may be\n // an answer to it with elements left out, and documents of a docType no doc request asks for are\n // reported below.\n const unrequested = new Set(match.unrequestedDocuments.map((document) => document.documentIndex))\n const answeredUseCases = new Set(match.attribution.useCases.map((useCase) => useCase.useCaseIndex))\n const answeredDocRequests = new Set(match.attribution.useCases.flatMap(({ documentSet }) => documentSet))\n const unanswered = new Set(\n match.useCases\n .filter((useCase) => !answeredUseCases.has(useCase.useCaseIndex))\n .flatMap((useCase) => useCase.documentSets.flat())\n )\n // The documents of the docType of a doc request of those use cases, and of an issuer it accepts.\n const mayAnswerUnanswered = new Set(\n match.docRequests\n .filter((docRequest) => unanswered.has(docRequest.docRequestIndex))\n .flatMap((docRequest) => [...docRequest.validDocuments, ...docRequest.failedDocuments])\n .filter((document) => document.docType.success && document.issuer?.success !== false)\n .map((document) => document.documentIndex)\n )\n const unattributed = match.attribution.documents.filter(\n (document) =>\n !unrequested.has(document.documentIndex) &&\n !mayAnswerUnanswered.has(document.documentIndex) &&\n !document.docRequestIndexes.some((docRequestIndex) => answeredDocRequests.has(docRequestIndex))\n )\n if (match.success && unattributed.length > 0) {\n const sets = match.attribution.useCases\n .map(({ useCaseIndex, documentSet }) => `use case ${useCaseIndex} with doc requests ${documentSet.join(', ')}`)\n .join('; ')\n onCheck({\n status: 'WARNING',\n check: 'Device response must only contain documents of one document set per use case',\n category: 'DOCUMENT_FORMAT',\n reason: `${unattributed.length === 1 ? 'Document' : 'Documents'} ${unattributed.map((document) => document.documentIndex).join(', ')} ${unattributed.length === 1 ? 'answers' : 'answer'} no doc request of the document sets the use cases are answered with (${sets})`,\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 if (!docRequest.success && docRequest.reason) return docRequest.reason\n\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 const reasons = [\n ...(document.issuer && !document.issuer.success ? [document.issuer.reason] : []),\n ...failedClaims.map((claim) => claim.reason),\n ]\n return `Document ${document.documentIndex}: ${reasons.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 zDeviceSigned = typedMap([\n ['nameSpaces', z.instanceof(DeviceNamespaces)],\n ['deviceAuth', z.instanceof(DeviceAuth)],\n] as const)\n\nexport type DeviceSignedDecodedStructure = z.output<typeof zDeviceSigned>\nexport type DeviceSignedEncodedStructure = z.input<typeof zDeviceSigned>\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(zDeviceSigned.in, zDeviceSigned.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 zErrorItems = 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 zErrorItems\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, zErrorItems } from './error-items'\nimport type { Namespace } from './namespace'\n\nconst zErrorsEncoded = z.map(z.string(), zErrorItems)\nconst zErrorsDecoded = z.map(z.string(), z.instanceof(ErrorItems))\n\nexport type ErrorsEncodedStructure = z.infer<typeof zErrorsEncoded>\nexport type ErrorsDecodedStructure = z.infer<typeof zErrorsDecoded>\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(zErrorsEncoded, zErrorsDecoded, {\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 zDocument = 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 zDocument>\nexport type DocumentEncodedStructure = z.input<typeof zDocument>\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(zDocument.in, zDocument.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 zDocumentError = z.map(z.string(), z.number())\n\nexport type DocumentErrorStructure = z.infer<typeof zDocumentError>\n\nexport type DocumentErrorOptions = {\n documentError: DocumentErrorStructure\n}\n\nexport class DocumentError extends CborStructure<DocumentErrorStructure> {\n public static override get encodingSchema() {\n return zDocumentError\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 type ElementMatch,\n issuerAuthCertificateChain,\n matchDeviceRequest,\n matchElements,\n matchIssuer,\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 UnsatisfiedDeviceRequestError,\n} from '../errors'\nimport type { AlternativeDataElementsSet } from './alternative-data-elements-set'\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 { IntentToRetain } from './intent-to-retain'\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\n/**\n * Whether a requested element is answered by one of its alternative sets, which a holder only\n * discloses when it chooses one: the credential does not have the element itself.\n */\nconst isAnsweredByAlternative = (match: ElementMatch) => match.options?.[0].alternativeElementSetIndex !== undefined\n\nconst zDeviceResponseEncoded = 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 zDeviceResponseDecoded = 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 zDeviceResponseEncoded>\nexport type DeviceResponseDecodedStructure = z.output<typeof zDeviceResponseDecoded>\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, or of every\n * doc request it answers, which then all have its docType. The document discloses the elements\n * all of them request, and counts as their document for `uniqueDocSetRequired` and the use cases.\n */\n docRequestIndex: number | Array<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 * For a requested element that has alternatives in the `requestInfo` of the doc request (ISO/IEC\n * TS 23220-4 7.2.1.3.2, 18013-5 second edition 10.2.4), the index into its `alternativeElementSets`\n * of the set to disclose in its place, per namespace and element. For a document that answers\n * several doc requests, the ones that request the element must have the same alternatives for it. Every element of the set is\n * disclosed, possibly in other namespaces. The `options` of the claims of `Holder.matchDeviceRequest`\n * list the sets the credential can disclose.\n *\n * An alternative set is only disclosed when it is chosen here, so that nothing is disclosed that\n * the holder was not shown. By default the element itself is disclosed, and a requested element the\n * credential does not have throws a `MissingRequestedElementError`, even when an alternative set\n * could answer it.\n *\n * Throws an `InvalidElementSelectionError` for an element the doc request does not request, a set\n * it does not have, an element that `elements` leaves out, a set that discloses an element that\n * `elements` leaves out, or an element that the doc requests of the document have different\n * alternatives for; and a `MissingRequestedElementError` for a set the credential does not have\n * every element of.\n */\n alternatives?: Record<Namespace, Record<DataElementIdentifier, number>>\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, and of the alternative sets chosen in `alternatives`, are\n * disclosed and authenticated, so a value that is not requested or that `elements` leaves out is\n * 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(zDeviceResponseEncoded.in, zDeviceResponseDecoded.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 /** The maximum size in bytes the status list of an mdoc may inflate to, 16 MiB by default. */\n maxStatusListDecompressedBytes?: number\n },\n ctx: Pick<MdocContext, 'cose' | 'x509' | 'crypto' | 'fetch' | 'fetchLimits'>\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 maxStatusListDecompressedBytes: options.maxStatusListDecompressedBytes,\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 // The x5chain is not signed, so issuers are matched against the validated chains.\n issuerCertificateChains: documentResults.map(({ trustedIssuanceChain }) => trustedIssuanceChain),\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 the doc requests it answers, authenticated with either a\n * device signature or a device MAC.\n */\n private static async createDocument(\n options: {\n docRequests: Array<{ docRequestIndex: number; docRequest: DocRequest }>\n sessionTranscript: SessionTranscript | Uint8Array\n issuerSigned: IssuerSigned\n elements?: Record<Namespace, Array<DataElementIdentifier>>\n alternatives?: Record<Namespace, Record<DataElementIdentifier, number>>\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 // 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 const docType = mobileSecurityObject.docType\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 for (const { docRequestIndex, docRequest } of options.docRequests) {\n if (docRequest.itemsRequest.docType !== docType) {\n throw new DocTypeMismatchError(\n `Credential has docType '${docType}', but doc request ${docRequestIndex} requests docType '${docRequest.itemsRequest.docType}'`\n )\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 ...DeviceResponse.mergeDocRequests(options.docRequests),\n docRequestIndexes: options.docRequests.map(({ docRequestIndex }) => docRequestIndex),\n issuerSigned: options.issuerSigned,\n keyAuthorizations,\n deviceNamespaces: options.deviceNamespaces,\n elements: options.elements,\n alternatives: options.alternatives,\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, or the alternative sets chosen for them, are disclosed,\n * from either source: a device-signed element that is not requested, or that `elements` leaves\n * out, is not disclosed.\n */\n private static selectElements(options: {\n namespaces: Map<Namespace, Map<DataElementIdentifier, IntentToRetain>>\n alternativeDataElements: Array<AlternativeDataElementsSet> | undefined\n /**\n * The requested elements that the doc requests have different alternatives for, which cannot be\n * chosen, with the doc requests that request them.\n */\n conflictingAlternatives: Array<{\n namespace: Namespace\n elementIdentifier: DataElementIdentifier\n docRequestIndexes: Array<number>\n }>\n /**\n * The doc requests the document answers, for the error messages.\n */\n docRequestIndexes: Array<number>\n issuerSigned: IssuerSigned\n keyAuthorizations: KeyAuthorizations | undefined\n deviceNamespaces?: DeviceNamespaces\n elements?: Record<Namespace, Array<DataElementIdentifier>>\n alternatives?: Record<Namespace, Record<DataElementIdentifier, number>>\n }) {\n const { claims } = matchElements({\n mode: 'holder',\n namespaces: options.namespaces,\n issuerSigned: options.issuerSigned,\n keyAuthorizations: options.keyAuthorizations,\n deviceNamespaces: options.deviceNamespaces,\n alternatives: options.alternativeDataElements,\n })\n\n const several = options.docRequestIndexes.length > 1\n const docRequests = several ? `doc requests ${options.docRequestIndexes.join(', ')}` : 'the doc request'\n const doNotRequest = `${docRequests} ${several ? 'do' : 'does'} not request`\n\n if (options.elements) {\n for (const [namespace, elementIdentifiers] of Object.entries(options.elements)) {\n for (const elementIdentifier of elementIdentifiers) {\n if (!options.namespaces.get(namespace)?.has(elementIdentifier)) {\n throw new InvalidElementSelectionError(\n `Element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but ${doNotRequest} 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 const requestedAlternatives = options.alternativeDataElements\n for (const [namespace, chosen] of Object.entries(options.alternatives ?? {})) {\n for (const [elementIdentifier, alternativeElementSetIndex] of Object.entries(chosen)) {\n if (!options.namespaces.get(namespace)?.has(elementIdentifier)) {\n throw new InvalidElementSelectionError(\n `Alternative set ${alternativeElementSetIndex} of element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but ${doNotRequest} the element`\n )\n }\n const sets = requestedAlternatives?.find(\n ({ requestedElement: [requestedNamespace, requestedIdentifier] }) =>\n requestedNamespace === namespace && requestedIdentifier === elementIdentifier\n )?.alternativeElementSets\n const conflict = options.conflictingAlternatives.find(\n (element) => element.namespace === namespace && element.elementIdentifier === elementIdentifier\n )\n if (conflict) {\n throw new InvalidElementSelectionError(\n `Alternative set ${alternativeElementSetIndex} of element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but doc requests ${conflict.docRequestIndexes.join(', ')} have different alternatives for it. Answer them with separate documents`\n )\n }\n if (!sets?.[alternativeElementSetIndex]) {\n throw new InvalidElementSelectionError(\n `Alternative set ${alternativeElementSetIndex} of element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but ${docRequests} ${several ? 'have' : 'has'} no such alternative set`\n )\n }\n if (options.elements && !getOwnProperty(options.elements, namespace)?.includes(elementIdentifier)) {\n throw new InvalidElementSelectionError(\n `Alternative set ${alternativeElementSetIndex} of element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but the element itself is not selected`\n )\n }\n }\n }\n\n // The element of each requested element left out of the selection, with that claim. One that the\n // credential does not have, and that an alternative set answers, has none to leave out.\n const declinedElements = new Map(\n claims.flatMap((match) =>\n match.element && !isAnsweredByAlternative(match) && !isSelected(match.claim)\n ? [[match.element, match.claim] as const]\n : []\n )\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) {\n const conflict = options.conflictingAlternatives.find(\n (element) => element.namespace === claim.namespace && element.elementIdentifier === claim.elementIdentifier\n )\n throw new MissingRequestedElementError(\n conflict\n ? `Element '${claim.elementIdentifier}' in namespace '${claim.namespace}' is not in the credential, and doc requests ${conflict.docRequestIndexes.join(', ')} have different alternatives for it. Answer them with separate documents`\n : match.claim.reason\n )\n }\n const { element } = match\n\n const alternativeElementSetIndex = getOwnProperty(\n getOwnProperty(options.alternatives, claim.namespace),\n claim.elementIdentifier\n )\n const chosen =\n alternativeElementSetIndex === undefined\n ? undefined\n : match.options?.find((option) => option.alternativeElementSetIndex === alternativeElementSetIndex)\n if (alternativeElementSetIndex !== undefined && !chosen) {\n throw new MissingRequestedElementError(\n `Alternative set ${alternativeElementSetIndex} of element '${claim.elementIdentifier}' in namespace '${claim.namespace}' is selected for disclosure, but the credential cannot disclose every element of it`\n )\n }\n\n // An alternative set is only disclosed when the holder chooses it, so that nothing is disclosed\n // that the holder was not shown: the requested element may be answered by elements in other\n // namespaces, which the claim does not describe.\n if (isAnsweredByAlternative(match) && !chosen) {\n throw new MissingRequestedElementError(\n `Element '${claim.elementIdentifier}' in namespace '${claim.namespace}' is not in the credential. Choose one of its alternative sets ${match.options?.map((option) => option.alternativeElementSetIndex).join(', ')} with \\`alternatives\\` to disclose in its place`\n )\n }\n\n // An alternative set (18013-5 second edition 10.2.4) is disclosed whole, each element in its\n // own namespace, which need not be the requested element's.\n const disclosedElements = chosen?.elements ?? [element]\n\n // An element left out must not be disclosed for another requested element, neither as an age\n // attestation that answers both (18013-5 7.2.5) nor in an alternative set, or leaving it out\n // would have no effect.\n for (const disclosed of disclosedElements) {\n const declined = declinedElements.get(disclosed)\n if (!declined) continue\n\n const selected = `Element '${claim.elementIdentifier}' in namespace '${claim.namespace}' is selected for disclosure`\n if (!chosen) {\n throw new InvalidElementSelectionError(\n `${selected}, but it is answered with '${disclosed.elementIdentifier}', which also answers '${declined.elementIdentifier}' that is not selected. Select both or neither`\n )\n }\n const answer =\n disclosed.namespace === declined.namespace && disclosed.elementIdentifier === declined.elementIdentifier\n ? `'${disclosed.elementIdentifier}' in namespace '${disclosed.namespace}'`\n : `'${disclosed.elementIdentifier}' in namespace '${disclosed.namespace}', which answers '${declined.elementIdentifier}' in namespace '${declined.namespace}'`\n throw new InvalidElementSelectionError(\n `${selected}, but it is answered with alternative set ${chosen.alternativeElementSetIndex}, which discloses ${answer} that is not selected. Select both, or choose another alternative set`\n )\n }\n\n for (const disclosed of disclosedElements) {\n if (!disclosed.issuerSignedItem) {\n const items = deviceNamespaces.get(disclosed.namespace) ?? new Map()\n items.set(disclosed.elementIdentifier, disclosed.elementValue)\n deviceNamespaces.set(disclosed.namespace, items)\n continue\n }\n\n const items = issuerNamespaces.get(disclosed.namespace) ?? []\n // An age attestation can answer more than one `age_over_NN` request, but is disclosed once.\n if (!items.includes(disclosed.issuerSignedItem)) items.push(disclosed.issuerSignedItem)\n issuerNamespaces.set(disclosed.namespace, items)\n }\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 `${several ? `Doc requests ${options.docRequestIndexes.join(', ')}` : '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${options.alternatives && Object.keys(options.alternatives).length > 0 ? ', or choose other alternative sets' : ''}`\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 /**\n * The doc requests a document answers, from its `docRequestIndex`.\n */\n private static findDocRequests(\n deviceRequest: DeviceRequest,\n document: Pick<DeviceResponseDocumentOptions, 'docRequestIndex'>\n ) {\n const docRequestIndexes = Array.from(\n new Set(typeof document.docRequestIndex === 'number' ? [document.docRequestIndex] : document.docRequestIndex)\n )\n if (docRequestIndexes.length === 0) throw new Error('A document has to answer at least one doc request')\n\n return docRequestIndexes.map((docRequestIndex) => ({\n docRequestIndex,\n docRequest: DeviceResponse.findDocRequest(deviceRequest, docRequestIndex),\n }))\n }\n\n /**\n * What the doc requests of a document request together: every element any of them requests, and\n * its alternatives. An element that more than one of them requests with different alternatives,\n * or without alternatives in one of them, is answered by itself only: an alternative set of one\n * doc request would not answer the other.\n */\n private static mergeDocRequests(docRequests: Array<{ docRequestIndex: number; docRequest: DocRequest }>) {\n const namespaces = new Map<Namespace, Map<DataElementIdentifier, IntentToRetain>>()\n for (const { docRequest } of docRequests) {\n for (const [namespace, elements] of docRequest.itemsRequest.namespaces) {\n const merged = namespaces.get(namespace) ?? new Map<DataElementIdentifier, IntentToRetain>()\n for (const [elementIdentifier, intentToRetain] of elements) {\n merged.set(elementIdentifier, (merged.get(elementIdentifier) ?? false) || intentToRetain)\n }\n namespaces.set(namespace, merged)\n }\n }\n\n const alternativeDataElements: Array<AlternativeDataElementsSet> = []\n const conflictingAlternatives: Array<{\n namespace: Namespace\n elementIdentifier: DataElementIdentifier\n docRequestIndexes: Array<number>\n }> = []\n for (const [namespace, elements] of namespaces) {\n for (const elementIdentifier of elements.keys()) {\n const requesting = docRequests.filter(({ docRequest }) =>\n docRequest.itemsRequest.namespaces.get(namespace)?.has(elementIdentifier)\n )\n const alternatives = requesting.map(({ docRequest }) =>\n docRequest.itemsRequest.requestInfo?.alternativeDataElements?.find(\n ({ requestedElement: [requestedNamespace, requestedIdentifier] }) =>\n requestedNamespace === namespace && requestedIdentifier === elementIdentifier\n )\n )\n const [first] = alternatives\n if (!first) {\n if (alternatives.some((alternative) => alternative)) {\n conflictingAlternatives.push({\n namespace,\n elementIdentifier,\n docRequestIndexes: requesting.map(({ docRequestIndex }) => docRequestIndex),\n })\n }\n continue\n }\n const sameSets = (alternative: AlternativeDataElementsSet | undefined) =>\n JSON.stringify(alternative?.alternativeElementSets) === JSON.stringify(first.alternativeElementSets)\n if (alternatives.every(sameSets)) {\n alternativeDataElements.push(first)\n } else {\n conflictingAlternatives.push({\n namespace,\n elementIdentifier,\n docRequestIndexes: requesting.map(({ docRequestIndex }) => docRequestIndex),\n })\n }\n }\n }\n\n return {\n namespaces,\n alternativeDataElements: alternativeDataElements.length > 0 ? alternativeDataElements : undefined,\n conflictingAlternatives,\n }\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 * Throw an `UnsatisfiedDeviceRequestError` when the documents do not answer the device request the\n * way its request information asks (ISO/IEC TS 23220-4 7.2.1.3): a document of an issuer its doc\n * request does not name, more than one document for a doc request that requires a unique document\n * set, or, when the device request carries use cases, a mandatory use case, or every use case, left\n * without a document set whose doc requests all have a document.\n *\n * Only which doc requests get a document is checked, not which elements are disclosed, so the\n * holder can still leave elements out. A doc request has a document when a document names it in\n * its `docRequestIndex`, as one document can answer several doc requests. A response without any\n * document is not checked, as that is how a holder declines a request it\n * cannot or does not want to satisfy (18013-5 second edition 10.2.1).\n *\n * A device request without use cases does not say whether it asks for all its doc requests or for\n * any one of them: ISO/IEC TS 23220-4 7.2.1.3.2 reads it as all of them, but the iOS DC API presents\n * it as alternatives, so readers use it that way (see `treatAmbiguousMultipleDocRequestsAsAlternatives`).\n * Which doc requests get a document is then not checked.\n */\n private static checkRequestInfo(deviceRequest: DeviceRequest, documents: Array<DeviceResponseDocumentOptions>) {\n const documentsPerDocRequest = new Map<number, number>()\n\n for (const [documentIndex, document] of documents.entries()) {\n for (const { docRequestIndex, docRequest } of DeviceResponse.findDocRequests(deviceRequest, document)) {\n const { requestInfo } = docRequest.itemsRequest\n documentsPerDocRequest.set(docRequestIndex, (documentsPerDocRequest.get(docRequestIndex) ?? 0) + 1)\n\n const issuer = matchIssuer(\n requestInfo?.issuerIdentifiers,\n issuerAuthCertificateChain(document.issuerSigned),\n 'x5chain of the IssuerAuth'\n )\n if (issuer && !issuer.success) {\n throw new UnsatisfiedDeviceRequestError(\n `Document ${documentIndex} answers doc request ${docRequestIndex}, but comes from an issuer it does not accept: ${issuer.reason}`\n )\n }\n\n if (requestInfo?.uniqueDocSetRequired && documentsPerDocRequest.get(docRequestIndex) === 2) {\n throw new UnsatisfiedDeviceRequestError(\n `More than one document answers doc request ${docRequestIndex}, but it requires a unique document set`\n )\n }\n }\n }\n\n const useCases = deviceRequest.deviceRequestInfo?.useCases\n if (!useCases || documents.length === 0) return\n\n const hasDocument = (docRequestIndex: number) => documentsPerDocRequest.has(docRequestIndex)\n const isSatisfied = (documentSets: Array<Array<number>>) => documentSets.some((set) => set.every(hasDocument))\n const answered = `they answer doc requests ${Array.from(documentsPerDocRequest.keys())\n .sort((a, b) => a - b)\n .join(', ')}`\n\n for (const [useCaseIndex, useCase] of useCases.entries()) {\n if (useCase.mandatory && !isSatisfied(useCase.documentSets)) {\n throw new UnsatisfiedDeviceRequestError(\n `Use case ${useCaseIndex} is mandatory, but the documents do not answer every doc request of any of its document sets (${answered})`\n )\n }\n }\n if (!useCases.some((useCase) => isSatisfied(useCase.documentSets))) {\n throw new UnsatisfiedDeviceRequestError(\n `None of the use cases has a document set whose doc requests the documents all answer (${answered})`\n )\n }\n }\n\n /**\n * Throw an `UnsatisfiedDeviceRequestError` when the response is larger than the smallest\n * `maximumResponseSize` of the doc requests, the size in bytes of the unencrypted device response\n * the reader can accept (ISO/IEC TS 23220-4 7.2.1.3.2).\n */\n private static checkResponseSize(deviceRequest: DeviceRequest, deviceResponse: DeviceResponse) {\n const limits = deviceRequest.docRequests.flatMap((docRequest, docRequestIndex) => {\n const maximumResponseSize = docRequest.itemsRequest.requestInfo?.maximumResponseSize\n return maximumResponseSize === undefined ? [] : [{ docRequestIndex, maximumResponseSize }]\n })\n if (limits.length === 0) return\n\n const limit = limits.reduce((smallest, current) =>\n current.maximumResponseSize < smallest.maximumResponseSize ? current : smallest\n )\n const size = deviceResponse.encode().length\n if (size > limit.maximumResponseSize) {\n throw new UnsatisfiedDeviceRequestError(\n `The device response is ${size} bytes, but doc request ${limit.docRequestIndex} accepts at most ${limit.maximumResponseSize}. Leave out elements or documents`\n )\n }\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 requests it answers through `docRequestIndex`. Elements and doc requests may be left out,\n * as long as the response still answers the request the way its request information asks: see\n * `Holder.createDeviceResponseForDeviceRequest` for what is refused.\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 DeviceResponse.checkRequestInfo(options.deviceRequest, options.documents)\n\n const documents = await Promise.all(\n options.documents.map((document) =>\n DeviceResponse.createDocument(\n {\n docRequests: DeviceResponse.findDocRequests(options.deviceRequest, document),\n sessionTranscript: options.sessionTranscript,\n issuerSigned: document.issuerSigned,\n elements: document.elements,\n alternatives: document.alternatives,\n deviceNamespaces: document.deviceNamespaces,\n signature: document.signature,\n mac: document.mac,\n },\n ctx\n )\n )\n )\n\n const deviceResponse = DeviceResponse.fromDocuments(documents)\n DeviceResponse.checkResponseSize(options.deviceRequest, deviceResponse)\n return deviceResponse\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 zEncryptedResponseData = typedMap([\n ['enc', zUint8Array],\n ['cipherText', zUint8Array],\n] as const)\n\nexport type EncryptedResponseDataDecodedStructure = z.output<typeof zEncryptedResponseData>\nexport type EncryptedResponseDataEncodedStructure = z.input<typeof zEncryptedResponseData>\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 zEncryptedResponseData\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 zEncryptedResponseEncoded = z.tuple([z.literal('dcapi'), z.map(z.unknown(), z.unknown())])\nconst zEncryptedResponseDecoded = z.instanceof(EncryptedResponseData)\n\nexport type EncryptedResponseEncodedStructure = z.infer<typeof zEncryptedResponseEncoded>\nexport type EncryptedResponseDecodedStructure = z.infer<typeof zEncryptedResponseDecoded>\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(zEncryptedResponseEncoded, zEncryptedResponseDecoded, {\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 zEncryptionParameters = typedMap([\n ['nonce', zUint8Array],\n ['recipientPublicKey', z.instanceof(CoseKey)],\n] as const)\n\nexport type EncryptionParametersDecodedStructure = z.output<typeof zEncryptionParameters>\nexport type EncryptionParametersEncodedStructure = z.input<typeof zEncryptionParameters>\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(zEncryptionParameters.in, zEncryptionParameters.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 zEncryptionInfoEncoded = z.tuple([z.literal('dcapi'), z.map(z.unknown(), z.unknown())])\nconst zEncryptionInfoDecoded = z.instanceof(EncryptionParameters)\n\nexport type EncryptionInfoEncodedStructure = z.infer<typeof zEncryptionInfoEncoded>\nexport type EncryptionInfoDecodedStructure = z.infer<typeof zEncryptionInfoDecoded>\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(zEncryptionInfoEncoded, zEncryptionInfoDecoded, {\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","import { HashAlgorithm } from '@owf/cose'\nimport type { MdocContext } from '../context'\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\n/**\n * The value of a protected `x5t` COSE header (RFC 9360) for the leaf of a certificate chain, with\n * SHA-256 as 18013-5 (second edition) 12.3.4 and 12.5.4 require.\n */\nexport const x5tHeaderValue = async (certificateChain: Array<Uint8Array>, ctx: Pick<MdocContext, 'crypto'>) => [\n HashAlgorithm.SHA256,\n await ctx.crypto.digest({ digestAlgorithm: 'SHA-256', bytes: certificateChain[0] }),\n]\n","import {\n type CoseKey,\n type DigestAlgorithm,\n ProtectedHeaders,\n RegisteredCwtHeaderClaimKey,\n type SignatureAlgorithm,\n UnprotectedHeaders,\n} from '@owf/cose'\nimport { stringToBytes } from '@owf/identity-common'\nimport type { MdocContext } from '../../context'\nimport { randomUnsignedInteger } from '../../utils/randomUnsignedInteger'\nimport { x5chainHeaderValue, x5tHeaderValue } 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 /**\n * Add a SHA-256 `x5t` of the leaf certificate to the protected header, as the second edition of\n * ISO/IEC 18013-5 recommends. Off by default, as the first edition has nothing but `alg` there.\n */\n includeX5t?: boolean\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<number, unknown>([[RegisteredCwtHeaderClaimKey.Algorithm, options.algorithm]]),\n })\n if (options.includeX5t) {\n protectedHeaders.headers.set(\n RegisteredCwtHeaderClaimKey.X5T,\n await x5tHeaderValue(options.certificates, this.ctx)\n )\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 /** The maximum size in bytes the status list of an mdoc may inflate to, 16 MiB by default. */\n maxStatusListDecompressedBytes?: number\n },\n ctx: Pick<MdocContext, 'cose' | 'x509' | 'crypto' | 'fetch' | 'fetchLimits'>\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' | 'crypto'>\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`. A requested\n * element the credential only answers with an alternative set is the exception: the holder has to\n * choose the set with `alternatives`.\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 /**\n * Create a device response for a device request, with one document per entry of `documents`.\n *\n * Throws an `UnsatisfiedDeviceRequestError` when the documents do not answer the device request\n * the way its request information asks (ISO/IEC TS 23220-4 7.2.1.3):\n *\n * - a document of an issuer its doc request does not name\n * - more than one document for a doc request with `uniqueDocSetRequired`\n * - when the device request carries use cases, a mandatory use case, or every use case, left\n * without a document for each doc request of one of its document sets. A document counts for\n * the doc requests its `docRequestIndex` names, so one document can answer several doc\n * requests of its docType. Without use cases this is not checked, as the iOS DC API presents\n * several doc requests as alternatives, see `treatAmbiguousMultipleDocRequestsAsAlternatives`\n * - a response larger than the smallest `maximumResponseSize` of the doc requests\n *\n * Elements can still be left out, and an empty `documents` declines the request.\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 type DeviceRequestInfo,\n type DeviceRequestInfoOptions,\n DeviceResponse,\n type DeviceResponseDocumentOptions,\n type DeviceResponseVerificationResult,\n DocRequest,\n type DocRequestInfo,\n type DocRequestInfoOptions,\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, x5tHeaderValue } 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 zBase64Url = 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 zIsoMdocDcApiRequest = z.object({\n deviceRequest: zBase64Url,\n encryptionInfo: zBase64Url,\n})\nexport type IsoMdocDcApiRequest = z.infer<typeof zIsoMdocDcApiRequest>\n\n/**\n * Response payload returned over the DC API (C.3), base64url-no-pad encoded CBOR.\n */\nexport const zIsoMdocDcApiResponse = z.object({\n response: zBase64Url,\n})\nexport type IsoMdocDcApiResponse = z.infer<typeof zIsoMdocDcApiResponse>\n\n/**\n * The response as it may be handed to {@link IsoMdocDcApi.decryptResponse}, normalized to the\n * base64url `response` string.\n */\nconst zIsoMdocDcApiResponseInput = z.union([zBase64Url, zIsoMdocDcApiResponse.transform(({ response }) => response)])\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 * Alternative data elements, issuer identifiers and the other request information of the doc\n * request (ISO/IEC TS 23220-4 7.2.1.3.2). Covered by its reader auth.\n */\n requestInfo?: DocRequestInfo | DocRequestInfoOptions\n }>\n /**\n * The use cases of the device request (ISO/IEC TS 23220-4 7.2.1.3.4): which doc requests answer\n * what. `version` then defaults to `'1.1'`. Reader auth covers each doc request, not this.\n */\n deviceRequestInfo?: DeviceRequestInfo | DeviceRequestInfoOptions\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 * Add a SHA-256 `x5t` of the leaf certificate to the protected header, as the second edition of\n * ISO/IEC 18013-5 recommends. Off by default, as the first edition has nothing but `alg` there.\n */\n includeX5t?: boolean\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, requestInfo }) => {\n const itemsRequest = ItemsRequest.create({ docType, namespaces, requestInfo })\n\n if (!options.readerAuth || !sessionTranscript) {\n return DocRequest.create({ itemsRequest })\n }\n\n const { signingKey, certificateChain, includeX5t } = 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<number, unknown>([\n [RegisteredCwtHeaderClaimKey.Algorithm, signingKey.algorithm],\n ...(includeX5t\n ? [[RegisteredCwtHeaderClaimKey.X5T, await x5tHeaderValue(certificateChain, ctx)] as [number, unknown]]\n : []),\n ]),\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({\n version: options.version,\n docRequests,\n deviceRequestInfo: options.deviceRequestInfo,\n })\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(zIsoMdocDcApiRequest, 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 requests 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<\n DeviceResponseDocumentOptions,\n 'issuerSigned' | 'docRequestIndex' | 'elements' | 'alternatives' | 'deviceNamespaces'\n > & {\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 alternatives: document.alternatives,\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 zIsoMdocDcApiResponseInput,\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 /** The maximum size in bytes the status list of an mdoc may inflate to, 16 MiB by default. */\n maxStatusListDecompressedBytes?: number\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose' | 'x509' | 'fetch' | 'fetchLimits'>\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 maxStatusListDecompressedBytes: options.maxStatusListDecompressedBytes,\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 /**\n * Add a SHA-256 `x5t` of the leaf certificate to the protected header, as the second edition of\n * ISO/IEC 18013-5 recommends. Off by default, as the first edition has nothing but `alg` there.\n */\n includeX5t?: boolean\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 /** The maximum size in bytes the status list of an mdoc may inflate to, 16 MiB by default. */\n maxStatusListDecompressedBytes?: number\n },\n ctx: Pick<MdocContext, 'cose' | 'x509' | 'crypto' | 'fetch' | 'fetchLimits'>\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 /**\n * See `issuerCertificateChains` of {@link matchDeviceRequest}: without them, no document\n * satisfies a doc request that names issuers, as the x5chain is not trusted.\n */\n issuerCertificateChains?: Array<Array<Uint8Array> | undefined>\n }): DeviceRequestMatchResult {\n return matchDeviceRequest({\n matchOptions: options.matchOptions,\n issuerCertificateChains: options.issuerCertificateChains,\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":";;;;;;;;;;;;;AAYA,IAAY,cAAL,yBAAA,aAAA;;CAEL,YAAA,4CAAA;;CAGA,YAAA,4CAAA;;CAGA,YAAA,8CAAA;;AACF,EAAA,CAAA,CAAA;;ACjBA,IAAa,WAAb,cAA8B,cAAc;CAC1C,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;;;;;;;;AA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O,MAAM,KAAK,IAAI,KAAK;GAAE,GAAG;GAAS;EAAW,CAAC;CACvD;AACF;;AChCA,IAAa,WAAb,MAAsB;CACpB,aAAoB,qBAClB,SAeA,KAC2C;EAM3C,QAJE,QAAQ,0BAA0B,iBAC9B,QAAQ,iBACR,eAAe,OAAO,QAAQ,cAAc,EAAA,CAE5B,OAAO,SAAS,GAAG;CAC3C;;;;;;;;;CAUA,OAAc,mBAAmB,SASJ;EAC3B,OAAO,mBAAmB;GACxB,cAAc,QAAQ;GACtB,yBAAyB,QAAQ;GACjC,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","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","z","z","z","z","Sign1","z","z","z","z","StatusListInfo","z","z","z","RegisteredCwtHeaderClaimKey","ProtectedHeaders","z","RegisteredCwtClaimKey","ProtectedHeaders","RegisteredCwtHeaderClaimKey","SignatureAlgorithm","verifyTokenStatusListJwt","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/alternative-data-elements-set.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/structureArray.ts","../src/utils/zodInteger.ts","../src/mdoc/models/use-case.ts","../src/mdoc/models/device-request-info.ts","../src/utils/ageOver.ts","../src/mdoc/models/doc-request-info.ts","../src/mdoc/models/items-request.ts","../src/mdoc/models/reader-authentication.ts","../src/mdoc/models/reader-auth.ts","../src/mdoc/models/doc-request.ts","../src/mdoc/models/device-request.ts","../src/utils/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/attribution.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'\nimport type { FetchCallback, FetchContext, FetchLimits } from '@owf/identity-common'\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\n/**\n * What a {@link MdocContext.fetch} call is retrieving. Lets an implementation apply policy —\n * caching, timeouts, retries — per resource rather than to every request alike.\n */\nexport type MdocFetchContext = FetchContext<MdocFetchType>\n\n/** What this library fetches: the status lists and identifier lists an MSO references. */\nexport type MdocFetchType = 'statusList' | 'identifierList'\n\nexport interface MdocContext {\n /**\n * Retrieves a resource over HTTP. `context` names what is being retrieved; the revocation lists\n * an MSO references are the only resources this library fetches. The body of the response is\n * read within {@link MdocContext.fetchLimits}, so `fetch` does not have to limit it.\n *\n * The global `fetch` satisfies this, as it ignores the third argument.\n */\n fetch: FetchCallback<MdocFetchType>\n\n /**\n * The maximum sizes of the status list and identifier list responses, 16 MiB each by default\n * (see `FetchLimits` of `@owf/identity-common`).\n */\n fetchLimits?: FetchLimits<MdocFetchType>\n\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 the path it validated with the leaf first and the\n * trusted root last.\n *\n * Only return the certificates of that path. The x5chain is in the unprotected header, so a\n * holder can add any certificate to it, and the `issuerIdentifiers` of a doc request are matched\n * against every certificate returned here: returning the whole x5chain with the trusted root\n * appended lets a document pass for any issuer whose certificate is added to it.\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 { IdentityError } from '@owf/identity-common'\nimport type { VerificationAssessment, VerificationCallback } from './check-callback.js'\n\n// biome-ignore format: no explanation\nexport class MdlError extends IdentityError {\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 * The documents of a device response do not answer the device request the way its request\n * information asks (ISO/IEC TS 23220-4 7.2.1.3): a document comes from an issuer the doc request\n * does not accept, more than one document answers a doc request that requires a unique document\n * set, the documents leave a mandatory use case of the device request unsatisfied, or every use\n * case, or the response is larger than the reader accepts.\n */\nexport class UnsatisfiedDeviceRequestError 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 UnableToExtractX5ChainFromJwtError extends MdlError {}\nexport class NoPublicKeySetOnStatusListError extends MdlError {}\nexport class InvalidSignatureError extends MdlError {}\n\n/**\n * RFC 9360: the end-entity certificate \"MUST be integrity protected by COSE\". An `x5chain` in the\n * unprotected header is therefore only accepted when a protected `x5t` matches its leaf.\n */\nexport class UnprotectedX5ChainNotBoundError extends MdlError {}\n\n/**\n * @deprecated A status list served as a JWT is now verified as a fallback rather than rejected, so\n * this error is no longer thrown.\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 — could not be used. Either one of the\n * claim requirements from ISO/IEC 18013-5 second edition 12.3.6 / the Token Status List\n * specification was not met (missing or mismatched subject, missing or passed expiration, or an\n * issuance time in the future), or a status list served as a JWT is malformed: not a well-formed\n * JWS, an unsupported `alg` or a `crit` header, or no readable `status_list`. Most of those JWT\n * checks run before the signature is verified, so this error does not by itself mean the list was\n * signed by its issuer.\n */\nexport class InvalidRevocationListError extends MdlError {}\n\n/**\n * The status list was verified, but the status of the MSO in it is not Valid, which ISO/IEC\n * 18013-5 second edition 12.3.6.1 requires. Unlike a list that fails verification, this is a\n * statement about the mdoc (Token Status List § 7 and § 8.3), so `uri`, `idx` and `status` are\n * carried as data rather than only in the message. It extends `InvalidRevocationListError`,\n * which a status that is not Valid was reported as before.\n */\nexport class StatusListEntryNotValidError extends InvalidRevocationListError {\n public readonly uri: string\n public readonly idx: number\n /** The status at `idx`, e.g. `1` for Invalid (revoked) or `2` for Suspended. */\n public readonly status: number\n\n public constructor(message: string, { uri, idx, status }: { uri: string; idx: number; status: number }) {\n super(message)\n this.uri = uri\n this.idx = idx\n this.status = status\n }\n}\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, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport type { Namespace } from './namespace'\n\n/**\n * A data element, by namespace and identifier (ISO/IEC TS 23220-4 7.2.1.3.2 `ElementReference`).\n */\nexport type ElementReference = [Namespace, DataElementIdentifier]\n\nconst zElementReference = z.tuple([z.string(), z.string()])\n\nconst zAlternativeDataElementsSet = typedMap([\n ['requestedElement', zElementReference],\n ['alternativeElementSets', z.array(z.array(zElementReference).min(1)).min(1)],\n] as const)\n\nexport type AlternativeDataElementsSetEncodedStructure = z.input<typeof zAlternativeDataElementsSet>\nexport type AlternativeDataElementsSetDecodedStructure = z.output<typeof zAlternativeDataElementsSet>\n\nexport type AlternativeDataElementsSetOptions = {\n requestedElement: ElementReference\n /**\n * The sets of elements that may be returned in place of the requested one, in the reader's order\n * of preference.\n */\n alternativeElementSets: Array<Array<ElementReference>>\n}\n\n/**\n * Elements that may be returned in place of a requested one (ISO/IEC TS 23220-4 7.2.1.3.2). Each set\n * answers the request on its own; the sets are in the reader's order of preference, the most\n * privacy-preserving first.\n */\nexport class AlternativeDataElementsSet extends CborStructure<\n AlternativeDataElementsSetEncodedStructure,\n AlternativeDataElementsSetDecodedStructure\n> {\n public static override get encodingSchema() {\n return zAlternativeDataElementsSet\n }\n\n public get requestedElement(): ElementReference {\n return this.structure.get('requestedElement')\n }\n\n public get alternativeElementSets(): Array<Array<ElementReference>> {\n return this.structure.get('alternativeElementSets')\n }\n\n public static create(options: AlternativeDataElementsSetOptions): AlternativeDataElementsSet {\n const map: AlternativeDataElementsSetDecodedStructure = new TypedMap([\n ['requestedElement', options.requestedElement],\n ['alternativeElementSets', options.alternativeElementSets],\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, 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 zBleOptions = 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 zBleOptions>\nexport type BleOptionsDecodedStructure = z.output<typeof zBleOptions>\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 zBleOptions\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 | {\n type: 'deviceRequestMatch'\n match: DeviceRequestMatchResult\n }\n | {\n /** The status of the MSO in its status list is not Valid. */\n type: 'statusListEntryNotValid'\n uri: string\n idx: number\n /** The status at `idx`, e.g. `1` for Invalid (revoked) or `2` for Suspended. */\n status: number\n }\n | {\n /** The identifier of the MSO is in its identifier list. */\n type: 'identifierListEntryRevoked'\n uri: string\n id: Uint8Array\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 zDeviceSignedItems = z.map(z.string(), z.unknown())\n\nexport type DeviceSignedItemsStructure = z.infer<typeof zDeviceSignedItems>\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 zDeviceSignedItems\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, zDeviceSignedItems } from './device-signed-items'\nimport type { Namespace } from './namespace'\n\nconst zDeviceNamespacesEncoded = z.map(z.string(), zDeviceSignedItems)\nconst zDeviceNamespacesDecoded = z.map(z.string(), z.instanceof(DeviceSignedItems))\n\nexport type DeviceNamespacesDecodedStructure = z.infer<typeof zDeviceNamespacesDecoded>\nexport type DeviceNamespacesEncodedStructure = z.infer<typeof zDeviceNamespacesEncoded>\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(zDeviceNamespacesEncoded, zDeviceNamespacesDecoded, {\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 zNfcOptions = typedMap([\n [NfcOptionsKeys.MaxCommandDataLength, z.number()],\n [NfcOptionsKeys.MaxResponseDataLength, z.number()],\n] as const)\n\nexport type NfcOptionsEncodedStructure = z.input<typeof zNfcOptions>\nexport type NfcOptionsDecodedStructure = z.output<typeof zNfcOptions>\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 zNfcOptions\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 zWifiOptions = 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 zWifiOptions>\nexport type WifiOptionsDecodedStructure = z.output<typeof zWifiOptions>\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 zWifiOptions\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 zDeviceRetrievalMethodEncoded = z.tuple([\n z.enum(DeviceRetrievalMethodType).or(z.number()),\n z.number(),\n z.map(z.unknown(), z.unknown()),\n])\n\nconst zDeviceRetrievalMethodDecoded = 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 zDeviceRetrievalMethodEncoded>\nexport type DeviceRetrievalMethodDecodedStructure = z.infer<typeof zDeviceRetrievalMethodDecoded>\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(zDeviceRetrievalMethodEncoded, zDeviceRetrievalMethodDecoded, {\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 zProtocolInfo = z.unknown()\nexport type ProtocolInfoStructure = z.infer<typeof zProtocolInfo>\n\nexport class ProtocolInfo extends CborStructure<ProtocolInfoStructure> {\n public static override get encodingSchema() {\n return zProtocolInfo\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 zSecurityEncoded = z.tuple([z.number(), z.instanceof(DataItem)])\n\nconst zSecurityDecoded = z.object({\n cipherSuiteIdentifier: z.number(),\n eDeviceKey: z.instanceof(EDeviceKey),\n})\n\nexport type SecurityEncodedStructure = z.infer<typeof zSecurityEncoded>\nexport type SecurityDecodedStructure = z.infer<typeof zSecurityDecoded>\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(zSecurityEncoded, zSecurityDecoded, {\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 zOidcEncoded = z.tuple([z.number(), z.string(), z.string()])\n\n// Easier structure for internal usage in class\nconst zOidcDecoded = z.object({\n version: z.number(),\n issuerUrl: z.string(),\n serverRetrievalToken: z.string(),\n})\n\nexport type OidcEncodedStructure = z.infer<typeof zOidcEncoded>\nexport type OidcDecodedStructure = z.infer<typeof zOidcDecoded>\nexport type OidcOptions = OidcDecodedStructure\n\nexport class Oidc extends CborStructure<OidcEncodedStructure, OidcDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(zOidcEncoded, zOidcDecoded, {\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 zWebApiEncoded = z.tuple([z.number(), z.string(), z.string()])\n\n// Easier structure for internal usage in class\nconst zWebApiDecoded = z.object({\n version: z.number(),\n issuerUrl: z.string(),\n serverRetrievalToken: z.string(),\n})\n\nexport type WebApiEncodedStructure = z.infer<typeof zWebApiEncoded>\nexport type WebApiDecodedStructure = z.infer<typeof zWebApiDecoded>\nexport type WebApiOptions = WebApiDecodedStructure\n\nexport class WebApi extends CborStructure<WebApiEncodedStructure, WebApiDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(zWebApiEncoded, zWebApiDecoded, {\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 zServerRetrievalMethod = typedMap([\n ['webApi', z.instanceof(WebApi).exactOptional()],\n ['oidc', z.instanceof(Oidc).exactOptional()],\n] as const)\n\nexport type ServerRetrievalMethodDecodedStructure = z.output<typeof zServerRetrievalMethod>\nexport type ServerRetrievalMethodEncodedStructure = z.input<typeof zServerRetrievalMethod>\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(zServerRetrievalMethod.in, zServerRetrievalMethod.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 zDeviceEngagement = 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 zDeviceEngagement>\nexport type DeviceEngagementDecodedStructure = z.output<typeof zDeviceEngagement>\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(zDeviceEngagement.in, zDeviceEngagement.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 zEngagementToAppHandover = zUint8Array\nexport type EngagementToAppHandoverStructure = z.infer<typeof zEngagementToAppHandover>\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 zEngagementToAppHandover\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 zIsoMdocDcApiHandoverEncoded = z.tuple([z.literal('dcapi'), zUint8Array])\nconst zIsoMdocDcApiHandoverDecoded = zUint8Array\n\nexport type IsoMdocDcApiHandoverEncodedStructure = z.infer<typeof zIsoMdocDcApiHandoverEncoded>\nexport type IsoMdocDcApiHandoverDecodedStructure = z.infer<typeof zIsoMdocDcApiHandoverDecoded>\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(zIsoMdocDcApiHandoverEncoded, zIsoMdocDcApiHandoverDecoded, {\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 zNfcHandoverEncoded = z.tuple([zUint8Array, zUint8Array.nullable()])\nconst zNfcHandoverDecoded = z.object({\n selectMessage: zUint8Array,\n requestMessage: zUint8Array.nullable(),\n})\n\nexport type NfcHandoverEncodedStructure = z.infer<typeof zNfcHandoverEncoded>\nexport type NfcHandoverDecodedStructure = z.infer<typeof zNfcHandoverDecoded>\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(zNfcHandoverEncoded, zNfcHandoverDecoded, {\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 zOid4vpDcApiDraft24HandoverInfo = z.tuple([z.string(), z.string(), z.string()])\nconst zOid4vpDcApiDraft24HandoverInfoDecoded = z.object({\n origin: z.string(),\n clientId: z.string(),\n nonce: z.string(),\n})\n\nexport type Oid4vpDcApiDraft24HandoverInfoEncodedStructure = z.infer<typeof zOid4vpDcApiDraft24HandoverInfo>\nexport type Oid4vpDcApiDraft24HandoverInfoDecodedStructure = z.infer<typeof zOid4vpDcApiDraft24HandoverInfoDecoded>\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(zOid4vpDcApiDraft24HandoverInfo, zOid4vpDcApiDraft24HandoverInfoDecoded, {\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 zOid4vpDcApiHandoverEncoded = z.tuple([z.literal('OpenID4VPDCAPIHandover'), zUint8Array])\nconst zOid4vpDcApiHandoverDecoded = zUint8Array\n\nexport type Oid4vpDcApiHandoverEncodedStructure = z.infer<typeof zOid4vpDcApiHandoverEncoded>\nexport type Oid4vpDcApiHandoverDecodedStructure = z.infer<typeof zOid4vpDcApiHandoverDecoded>\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(zOid4vpDcApiHandoverEncoded, zOid4vpDcApiHandoverDecoded, {\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 zOid4vpDcApiHandoverInfoEncoded = z.tuple([z.string(), z.string(), zUint8Array.nullable()])\nconst zOid4vpDcApiHandoverInfoDecoded = z.object({\n origin: z.string(),\n nonce: z.string(),\n jwkThumbprint: zUint8Array.nullable(),\n})\n\nexport type Oid4vpDcApiHandoverInfoEncodedStructure = z.infer<typeof zOid4vpDcApiHandoverInfoEncoded>\nexport type Oid4vpDcApiHandoverInfoDecodedStructure = z.infer<typeof zOid4vpDcApiHandoverInfoDecoded>\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(zOid4vpDcApiHandoverInfoEncoded, zOid4vpDcApiHandoverInfoDecoded, {\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 zOid4vpDraft18HandoverEncoded = z.tuple([zUint8Array, zUint8Array, z.string()])\nconst zOid4vpDraft18HandoverDecoded = z.object({\n clientIdHash: zUint8Array,\n responseUriHash: zUint8Array,\n nonce: z.string(),\n})\n\nexport type Oid4vpDraft18HandoverEncodedStructure = z.infer<typeof zOid4vpDraft18HandoverEncoded>\nexport type Oid4vpDraft18HandoverDecodedStructure = z.infer<typeof zOid4vpDraft18HandoverDecoded>\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(zOid4vpDraft18HandoverEncoded, zOid4vpDraft18HandoverDecoded, {\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 zOid4vpHandoverEncoded = z.tuple([z.literal('OpenID4VPHandover'), zUint8Array])\nconst zOid4vpHandoverDecoded = zUint8Array\n\nexport type Oid4vpHandoverEncodedStructure = z.infer<typeof zOid4vpHandoverEncoded>\nexport type Oid4vpHandoverDecodedStructure = z.infer<typeof zOid4vpHandoverDecoded>\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(zOid4vpHandoverEncoded, zOid4vpHandoverDecoded, {\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 zOid4vpHandoverInfoEncoded = z.tuple([z.string(), z.string(), zUint8Array.nullable(), z.string()])\nconst zOid4vpHandoverInfoDecoded = 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 zOid4vpHandoverInfoEncoded>\nexport type Oid4vpHandoverInfoDecodedStructure = z.infer<typeof zOid4vpHandoverInfoDecoded>\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(zOid4vpHandoverInfoEncoded, zOid4vpHandoverInfoDecoded, {\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 zOid4vpIaeHandoverEncoded = z.tuple([z.literal('OpenID4VCIIAEHandover'), zUint8Array])\nconst zOid4vpIaeHandoverDecoded = zUint8Array\n\nexport type Oid4vpIaeHandoverEncodedStructure = z.infer<typeof zOid4vpIaeHandoverEncoded>\nexport type Oid4vpIaeHandoverDecodedStructure = z.infer<typeof zOid4vpIaeHandoverDecoded>\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(zOid4vpIaeHandoverEncoded, zOid4vpIaeHandoverDecoded, {\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 zOid4vpIaeHandoverInfoEncoded = z.tuple([z.string(), z.string(), zUint8Array.nullable()])\nconst zOid4vpIaeHandoverInfoDecoded = z.object({\n interactiveAuthorizationEndpoint: z.string(),\n nonce: z.string(),\n jwkThumbprint: zUint8Array.nullable(),\n})\n\nexport type Oid4vpIaeHandoverInfoEncodedStructure = z.infer<typeof zOid4vpIaeHandoverInfoEncoded>\nexport type Oid4vpIaeHandoverInfoDecodedStructure = z.infer<typeof zOid4vpIaeHandoverInfoDecoded>\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(zOid4vpIaeHandoverInfoEncoded, zOid4vpIaeHandoverInfoDecoded, {\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 zQrHandover = z.null()\nexport type QrHandoverStructure = z.infer<typeof zQrHandover>\n\nexport class QrHandover extends Handover<QrHandoverStructure> {\n public static override get encodingSchema() {\n return zQrHandover\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 zSessionTranscriptEncoded = z.tuple([\n z.instanceof<typeof DataItem<DeviceEngagementEncodedStructure>>(DataItem).nullable(),\n z.instanceof<typeof DataItem<EReaderKeyEncodedStructure>>(DataItem).nullable(),\n z.unknown(),\n])\n\nconst zSessionTranscriptDecoded = 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 zSessionTranscriptDecoded>\nexport type SessionTranscriptEncodedStructure = z.infer<typeof zSessionTranscriptEncoded>\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(zSessionTranscriptEncoded, zSessionTranscriptDecoded, {\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, zSessionTranscriptEncoded } from './session-transcript'\n\nconst zDeviceAuthenticationEncoded = z.tuple([\n z.literal('DeviceAuthentication'),\n zSessionTranscriptEncoded,\n z.string(),\n z.instanceof<typeof DataItem<DeviceNamespacesEncodedStructure>>(DataItem),\n])\n\nconst zDeviceAuthenticationDecoded = z.object({\n sessionTranscript: z.instanceof(SessionTranscript),\n docType: z.string(),\n deviceNamespaces: z.instanceof(DeviceNamespaces),\n})\n\nexport type DeviceAuthenticationDecodedStructure = z.infer<typeof zDeviceAuthenticationDecoded>\nexport type DeviceAuthenticationEncodedStructure = z.infer<typeof zDeviceAuthenticationEncoded>\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(zDeviceAuthenticationEncoded, zDeviceAuthenticationDecoded, {\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 zDeviceAuth = 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 zDeviceAuthDecoded = zDeviceAuth.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 zDeviceAuth>\nexport type DeviceAuthEncodedStructure = z.input<typeof zDeviceAuth>\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(zDeviceAuth.in, zDeviceAuthDecoded, {\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 deviceSignature.verifySignature(\n { key: deviceKey, detachedPayload: deviceAuthenticationBytes },\n ctx.cose.sign1\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 zKeyAuthorizations = 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 zKeyAuthorizations>\nexport type KeyAuthorizationsDecodedStructure = z.output<typeof zKeyAuthorizations>\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 zKeyAuthorizations\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 zKeyInfo = z.map(z.number(), z.unknown())\n\nexport type KeyInfoEncodedStructure = z.input<typeof zKeyInfo>\nexport type KeyInfoDecodedStructure = z.output<typeof zKeyInfo>\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 zKeyInfo\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 zDeviceKeyInfo = 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 zDeviceKeyInfo>\nexport type DeviceKeyInfoEncodedStructure = z.input<typeof zDeviceKeyInfo>\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(zDeviceKeyInfo.in, zDeviceKeyInfo.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 { AnyTypedMap } from '@owf/cose'\n\n/**\n * `typedMap` decode and encode hooks for a key whose value is an array of nested structures, such as\n * the use cases of a `DeviceRequestInfo`. Decoding turns each encoded map into its structure with\n * `decode`, encoding turns each structure back into its encoded map. A value that is not an array is\n * left as is, for the schema to reject.\n */\nexport const structureArrayHooks = <Structure extends { encodedStructure: unknown }>(\n key: string,\n decode: (encoded: unknown) => Structure\n) => ({\n decode: (input: Map<unknown, unknown>, originalDecode: (input: Map<unknown, unknown>) => AnyTypedMap) => {\n const map = originalDecode(input)\n const value = input.get(key)\n if (Array.isArray(value)) map.set(key, value.map(decode))\n return map\n },\n encode: (output: AnyTypedMap, originalEncode: (output: AnyTypedMap) => Map<unknown, unknown>) => {\n const map = originalEncode(output)\n const value: unknown = output.get(key)\n if (Array.isArray(value))\n map.set(\n key,\n (value as Array<Structure>).map((structure) => structure.encodedStructure)\n )\n return map\n },\n})\n","import { z } from 'zod'\n\nconst MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER)\nconst MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER)\n\n/**\n * An integer as cbor-x decodes it: a number, or a bigint when the encoder wrote it in 8 bytes,\n * whatever its value. Only values a number holds exactly are accepted; read them with `Number()`.\n */\nexport const zInteger = z.union([z.number().int(), z.bigint().min(MIN_SAFE).max(MAX_SAFE)])\n\n/**\n * A non-negative {@link zInteger}, a CDDL `uint`.\n */\nexport const zUnsignedInteger = z.union([z.number().int().nonnegative(), z.bigint().nonnegative().max(MAX_SAFE)])\n","import { CborStructure, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { zInteger, zUnsignedInteger } from '../../utils/zodInteger'\n\nconst zUseCase = typedMap([\n ['mandatory', z.boolean()],\n ['purposeHints', z.map(z.string(), zInteger).exactOptional()],\n ['documentSets', z.array(z.array(zUnsignedInteger).min(1)).min(1)],\n] as const)\n\nexport type UseCaseEncodedStructure = z.input<typeof zUseCase>\nexport type UseCaseDecodedStructure = z.output<typeof zUseCase>\n\nexport type UseCaseOptions = {\n /**\n * Whether the use case has to be satisfied for the device request to be.\n */\n mandatory: boolean\n /**\n * Why the reader asks, per purpose controller, as codes of a registry a profile defines.\n */\n purposeHints?: Map<string, number>\n /**\n * The document sets that answer the use case, each a list of indexes into `docRequests`.\n */\n documentSets: Array<Array<number>>\n}\n\n/**\n * A use case of a device request (ISO/IEC TS 23220-4 7.2.1.3.4): the doc requests, by index into\n * `docRequests`, that answer it. Exactly one document set has to be returned for the use case to be\n * satisfied, every doc request of that set included.\n */\nexport class UseCase extends CborStructure<UseCaseEncodedStructure, UseCaseDecodedStructure> {\n public static override get encodingSchema() {\n return zUseCase\n }\n\n public get mandatory() {\n return this.structure.get('mandatory')\n }\n\n public get purposeHints(): Map<string, number> | undefined {\n const purposeHints = this.structure.get('purposeHints')\n return purposeHints && new Map(Array.from(purposeHints, ([controller, code]) => [controller, Number(code)]))\n }\n\n public get documentSets(): Array<Array<number>> {\n return this.structure.get('documentSets').map((set) => set.map(Number))\n }\n\n public static create(options: UseCaseOptions): UseCase {\n const map: UseCaseDecodedStructure = new TypedMap([['mandatory', options.mandatory]])\n if (options.purposeHints) map.set('purposeHints', options.purposeHints)\n map.set('documentSets', options.documentSets)\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 { structureArrayHooks } from '../../utils/structureArray'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\nimport { UseCase, type UseCaseEncodedStructure, type UseCaseOptions } from './use-case'\n\nconst zDeviceRequestInfo = typedMap(\n [['useCases', z.array(z.instanceof(UseCase)).min(1).exactOptional()]] as const,\n structureArrayHooks('useCases', (useCase) => UseCase.fromEncodedStructure(useCase as UseCaseEncodedStructure))\n)\n\nexport type DeviceRequestInfoEncodedStructure = z.input<typeof zDeviceRequestInfo>\nexport type DeviceRequestInfoDecodedStructure = z.output<typeof zDeviceRequestInfo>\n\nexport type DeviceRequestInfoOptions = {\n useCases?: Array<UseCase | UseCaseOptions>\n}\n\n/**\n * Information on a device request as a whole, the `deviceRequestInfo` of a `DeviceRequest`\n * (ISO/IEC TS 23220-4 7.2.1.3.4, taken up by the second edition of ISO/IEC 18013-5): which doc\n * requests answer which use case.\n *\n * Embedded as `DeviceRequestInfoBytes` (tag 24), so the bytes are kept as received.\n */\nexport class DeviceRequestInfo extends OriginalBytesCborStructure<\n DeviceRequestInfoEncodedStructure,\n DeviceRequestInfoDecodedStructure\n> {\n public static override get encodingSchema() {\n return zDeviceRequestInfo\n }\n\n public get useCases() {\n return this.structure.get('useCases')\n }\n\n public static create(options: DeviceRequestInfoOptions): DeviceRequestInfo {\n const map: DeviceRequestInfoDecodedStructure = new TypedMap([])\n\n if (options.useCases !== undefined) {\n map.set(\n 'useCases',\n options.useCases.map((useCase) => (useCase instanceof UseCase ? useCase : UseCase.create(useCase)))\n )\n }\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 { CborStructure, TypedMap, typedMap, zUint8Array } from '@owf/cose'\nimport { z } from 'zod'\nimport { structureArrayHooks } from '../../utils/structureArray'\nimport { zUnsignedInteger } from '../../utils/zodInteger'\nimport {\n AlternativeDataElementsSet,\n type AlternativeDataElementsSetEncodedStructure,\n type AlternativeDataElementsSetOptions,\n} from './alternative-data-elements-set'\n\nconst zDocRequestInfo = typedMap(\n [\n ['alternativeDataElements', z.array(z.instanceof(AlternativeDataElementsSet)).min(1).exactOptional()],\n ['issuerIdentifiers', z.array(zUint8Array).min(1).exactOptional()],\n ['uniqueDocSetRequired', z.boolean().exactOptional()],\n ['maximumResponseSize', zUnsignedInteger.exactOptional()],\n ] as const,\n structureArrayHooks('alternativeDataElements', (set) =>\n AlternativeDataElementsSet.fromEncodedStructure(set as AlternativeDataElementsSetEncodedStructure)\n )\n)\n\nexport type DocRequestInfoEncodedStructure = z.input<typeof zDocRequestInfo>\nexport type DocRequestInfoDecodedStructure = z.output<typeof zDocRequestInfo>\n\nexport type DocRequestInfoOptions = {\n alternativeDataElements?: Array<AlternativeDataElementsSet | AlternativeDataElementsSetOptions>\n /**\n * Key identifiers of the authority key identifier of an acceptable issuer certificate. An mdoc\n * only satisfies the doc request when one of them is the authority key identifier of a certificate\n * in its chain: for a verifier the chain it validated, as the x5chain is unprotected, and for a\n * holder the x5chain of its IssuerAuth.\n */\n issuerIdentifiers?: Array<Uint8Array>\n uniqueDocSetRequired?: boolean\n /**\n * The largest unencrypted DeviceResponse, in bytes, the reader accepts.\n */\n maximumResponseSize?: number\n /**\n * Entries a profile adds to `requestInfo`, such as the `euWrprc` registration certificate of ETSI TS\n * 119 472-2 clause 5.3.2. The entries above take precedence over one with the same key.\n */\n extensions?: Record<string, unknown>\n}\n\n/**\n * Additional information on a doc request, the `requestInfo` of an `ItemsRequest` (ISO/IEC TS\n * 23220-4 7.2.1.3.2, taken up by the second edition of ISO/IEC 18013-5).\n *\n * Keys this structure does not know are kept, so that an `ItemsRequest` re-encodes as received.\n */\nexport class DocRequestInfo extends CborStructure<DocRequestInfoEncodedStructure, DocRequestInfoDecodedStructure> {\n public static override get encodingSchema() {\n return zDocRequestInfo\n }\n\n public get alternativeDataElements() {\n return this.structure.get('alternativeDataElements')\n }\n\n public get issuerIdentifiers() {\n return this.structure.get('issuerIdentifiers')\n }\n\n public get uniqueDocSetRequired() {\n return this.structure.get('uniqueDocSetRequired')\n }\n\n public get maximumResponseSize() {\n const maximumResponseSize = this.structure.get('maximumResponseSize')\n return maximumResponseSize === undefined ? undefined : Number(maximumResponseSize)\n }\n\n /**\n * An entry of `requestInfo` by key, such as a profile extension. An entry this structure does not\n * define is returned as decoded, without validation.\n */\n public getExtension(key: string): unknown {\n return this.structure.get(key as never)\n }\n\n public static create(options: DocRequestInfoOptions): DocRequestInfo {\n const map: DocRequestInfoDecodedStructure = TypedMap.fromObject(options.extensions ?? {})\n\n if (options.alternativeDataElements !== undefined) {\n map.set(\n 'alternativeDataElements',\n options.alternativeDataElements.map((set) =>\n set instanceof AlternativeDataElementsSet ? set : AlternativeDataElementsSet.create(set)\n )\n )\n }\n if (options.issuerIdentifiers !== undefined) map.set('issuerIdentifiers', options.issuerIdentifiers)\n if (options.uniqueDocSetRequired !== undefined) map.set('uniqueDocSetRequired', options.uniqueDocSetRequired)\n if (options.maximumResponseSize !== undefined) map.set('maximumResponseSize', options.maximumResponseSize)\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 { describeAgeOverLimitViolations, findAgeOverRequestLimitViolations } from '../../utils/ageOver'\nimport { AgeOverLimitExceededError } from '../errors'\nimport { OriginalBytesCborStructure } from '../original-bytes-cbor-structure'\nimport type { DataElementIdentifier } from './data-element-identifier'\nimport { DocRequestInfo, type DocRequestInfoOptions } from './doc-request-info'\nimport type { DocType } from './doctype'\nimport type { IntentToRetain } from './intent-to-retain'\nimport type { Namespace } from './namespace'\n\nconst zNamespaces = z.map(z.string(), z.map(z.string(), z.boolean()))\n\n// Zod schema for ItemsRequest\nconst zItemsRequest = typedMap(\n [\n ['docType', z.string()],\n ['nameSpaces', zNamespaces],\n ['requestInfo', z.instanceof(DocRequestInfo).exactOptional()],\n ] as const,\n {\n decode: (input, originalDecode) => {\n const map = originalDecode(input)\n // Anything but a map is left for the schema to reject.\n const requestInfo = input.get('requestInfo')\n if (requestInfo instanceof Map) map.set('requestInfo', DocRequestInfo.fromEncodedStructure(requestInfo))\n return map\n },\n encode: (output, originalEncode) => {\n const map = originalEncode(output)\n const requestInfo = output.get('requestInfo')\n if (requestInfo) map.set('requestInfo', requestInfo.encodedStructure)\n return map\n },\n }\n)\n\nexport type ItemsRequestEncodedStructure = z.input<typeof zItemsRequest>\nexport type ItemsRequestDecodedStructure = z.output<typeof zItemsRequest>\n\ntype NamespacesStructure = z.infer<typeof zNamespaces>\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 requestInfo?: DocRequestInfo | DocRequestInfoOptions\n}\n\nexport class ItemsRequest extends OriginalBytesCborStructure<\n ItemsRequestEncodedStructure,\n ItemsRequestDecodedStructure\n> {\n public static override get encodingSchema() {\n return zItemsRequest\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 * The `requestInfo` of ISO/IEC TS 23220-4 7.2.1.3.2.\n */\n public get requestInfo() {\n return this.structure.get('requestInfo')\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: ItemsRequestDecodedStructure = new TypedMap([\n ['docType', options.docType],\n ['nameSpaces', namespaces],\n ])\n if (options.requestInfo) {\n structure.set(\n 'requestInfo',\n options.requestInfo instanceof DocRequestInfo ? options.requestInfo : DocRequestInfo.create(options.requestInfo)\n )\n }\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(structure)\n }\n}\n","import { CborStructure, DataItem } from '@owf/cose'\nimport { z } from 'zod'\nimport { ItemsRequest, type ItemsRequestEncodedStructure } from './items-request'\nimport { SessionTranscript, zSessionTranscriptEncoded } from './session-transcript'\n\nconst zReaderAuthenticationEncoded = z.tuple([\n z.literal('ReaderAuthentication'),\n zSessionTranscriptEncoded,\n z.instanceof<typeof DataItem<ItemsRequestEncodedStructure>>(DataItem),\n])\n\nconst zReaderAuthenticationDecoded = z.object({\n sessionTranscript: z.instanceof(SessionTranscript),\n itemsRequest: z.instanceof(ItemsRequest),\n})\n\nexport type ReaderAuthenticationDecodedStructure = z.infer<typeof zReaderAuthenticationDecoded>\nexport type ReaderAuthenticationEncodedStructure = z.infer<typeof zReaderAuthenticationEncoded>\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(zReaderAuthenticationEncoded, zReaderAuthenticationDecoded, {\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, verifyX5t } 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' | 'crypto'>\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 // ISO/IEC 18013-5 (second edition) § 12.5.4: an x5t, if present, shall use SHA-256.\n const x5tCheck = 'The x5t in the protected header, if present, must be SHA-256 and match the reader certificate'\n try {\n await verifyX5t(this, this.certificate, ctx.crypto)\n onCheck({ status: 'PASSED', check: x5tCheck })\n } catch (err) {\n onCheck({ status: 'FAILED', check: x5tCheck, reason: err instanceof Error ? err.message : 'Unknown error' })\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 zDocRequest = typedMap([\n ['itemsRequest', z.instanceof(ItemsRequest)],\n ['readerAuth', z.instanceof(ReaderAuth).exactOptional()],\n] as const)\n\nexport type DocRequestDecodedStructure = z.output<typeof zDocRequest>\nexport type DocRequestEncodedStructure = z.input<typeof zDocRequest>\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(zDocRequest.in, zDocRequest.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, DataItem, TypedMap, typedMap } from '@owf/cose'\nimport { z } from 'zod'\nimport { DeviceRequestInfo, type DeviceRequestInfoOptions } from './device-request-info'\nimport { DocRequest, type DocRequestEncodedStructure } from './doc-request'\n\nconst zDeviceRequest = typedMap([\n ['version', z.string()],\n ['docRequests', z.array(z.instanceof(DocRequest))],\n ['deviceRequestInfo', z.instanceof(DeviceRequestInfo).exactOptional()],\n] as const)\n\n// Every document set of a use case points at doc requests of this device request.\nconst zDeviceRequestOutput = zDeviceRequest.out.superRefine((map, ctx) => {\n // A missing or invalid docRequests is reported by the schema itself.\n const docRequests: unknown = map.get('docRequests')\n if (!Array.isArray(docRequests)) return\n const docRequestCount = docRequests.length\n map.get('deviceRequestInfo')?.useCases?.forEach((useCase, useCaseIndex) => {\n const missing = Array.from(new Set(useCase.documentSets.flat())).filter((id) => id >= docRequestCount)\n if (missing.length === 0) return\n ctx.addIssue({\n code: 'custom',\n path: ['deviceRequestInfo', 'useCases', useCaseIndex, 'documentSets'],\n message: `Doc request ${missing.join(', ')} ${missing.length === 1 ? 'does' : 'do'} not exist, the device request has ${docRequestCount}`,\n })\n })\n})\n\nexport type DeviceRequestDecodedStructure = z.output<typeof zDeviceRequest>\nexport type DeviceRequestEncodedStructure = z.input<typeof zDeviceRequest>\n\nexport type DeviceRequestOptions = {\n /**\n * Defaults to `'1.1'` when `deviceRequestInfo` is given and to `'1.0'` otherwise, as the second\n * edition of ISO/IEC 18013-5 asks (10.2.2).\n */\n version?: string\n docRequests: Array<DocRequest>\n deviceRequestInfo?: DeviceRequestInfo | DeviceRequestInfoOptions\n}\n\nexport class DeviceRequest extends CborStructure<DeviceRequestEncodedStructure, DeviceRequestDecodedStructure> {\n public static override get encodingSchema() {\n return z.codec(zDeviceRequest.in, zDeviceRequestOutput, {\n decode: (input) => {\n const map: DeviceRequestDecodedStructure = TypedMap.fromMap(input)\n // Anything but an array is left for the schema to reject.\n const docRequests = input.get('docRequests')\n if (Array.isArray(docRequests)) {\n map.set(\n 'docRequests',\n docRequests.map((dr) => DocRequest.fromEncodedStructure(dr as DocRequestEncodedStructure))\n )\n }\n\n // Anything but a data item is left for the schema to reject.\n const deviceRequestInfo = input.get('deviceRequestInfo')\n if (deviceRequestInfo instanceof DataItem) {\n map.set('deviceRequestInfo', DeviceRequestInfo.fromDataItem(deviceRequestInfo))\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 const deviceRequestInfo = output.get('deviceRequestInfo')\n if (deviceRequestInfo) map.set('deviceRequestInfo', deviceRequestInfo.asDataItem)\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 /**\n * The `deviceRequestInfo` of ISO/IEC TS 23220-4 7.2.1.3.4.\n */\n public get deviceRequestInfo() {\n return this.structure.get('deviceRequestInfo')\n }\n\n public static create(options: DeviceRequestOptions): DeviceRequest {\n const deviceRequestInfo =\n options.deviceRequestInfo instanceof DeviceRequestInfo || options.deviceRequestInfo === undefined\n ? options.deviceRequestInfo\n : DeviceRequestInfo.create(options.deviceRequestInfo)\n\n const map: DeviceRequestDecodedStructure = new TypedMap([\n ['version', options.version ?? (deviceRequestInfo ? '1.1' : '1.0')],\n ['docRequests', options.docRequests],\n ])\n if (deviceRequestInfo) map.set('deviceRequestInfo', deviceRequestInfo)\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 zIdentifierListInfo = typedMap([\n ['id', zUint8Array],\n ['uri', z.string()],\n ['certificate', zUint8Array.exactOptional()],\n])\n\nexport type IdentifierListInfoDecodedStructure = z.output<typeof zIdentifierListInfo>\nexport type IdentifierListInfoEncodedStructure = z.input<typeof zIdentifierListInfo>\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 zIdentifierListInfo\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 zStatus = typedMap([\n ['status_list', z.instanceof(StatusListInfo).exactOptional()],\n ['identifier_list', z.instanceof(IdentifierListInfo).exactOptional()],\n])\n\nexport type StatusDecodedStructure = z.output<typeof zStatus>\nexport type StatusEncodedStructure = z.input<typeof zStatus>\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(zStatus.in, zStatus.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 zValidityInfo = 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 zValidityInfo>\nexport type ValidityInfoDecodedStructure = z.output<typeof zValidityInfo>\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 zValidityInfo\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 zValueDigests = z.map(z.string(), z.map(z.number(), zUint8Array))\n\nexport type ValueDigestsStructure = z.infer<typeof zValueDigests>\n\nexport type ValueDigestOptions = {\n digests: ValueDigestsStructure\n}\n\nexport class ValueDigests extends CborStructure<ValueDigestsStructure> {\n public static override get encodingSchema() {\n return zValueDigests\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 zMobileSecurityObject = 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 zMobileSecurityObject>\nexport type MobileSecurityObjectEncodedStructure = z.input<typeof zMobileSecurityObject>\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(zMobileSecurityObject.in, zMobileSecurityObject.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 const MdocMediaTypes = {\n IdentifierListCwt: 'application/identifierlist+cwt',\n} as const\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(MdocMediaTypes.IdentifierListCwt, {\n error: `Typ (protected header 16) shall be '${MdocMediaTypes.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 zIdentifierInfo = z.map(z.union([z.string(), z.number()]), z.unknown())\n\nconst zIdentifierList = typedMap(\n [\n ['identifiers', z.map(zUint8Array, zIdentifierInfo)],\n ['aggregation_uri', z.string().exactOptional()],\n ],\n { allowAdditionalKeys: true }\n)\n\nexport type IdentifierListDecodedStructure = z.output<typeof zIdentifierList>\nexport type IdentifierListEncodedStructure = z.input<typeof zIdentifierList>\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 zIdentifierList\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 zIdentifierListCwtPayload = 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 zIdentifierListCwtPayload>\nexport type IdentifierListCwtPayloadDecodedStructure = z.infer<typeof zIdentifierListCwtPayload>\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(zIdentifierListCwtPayload.in, zIdentifierListCwtPayload.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 { fetchWithLimits, hex, IdentityCommonError, isMediaType } from '@owf/identity-common'\nimport type { MdocContext } from '../../context'\nimport { IdentifierFoundInRevokedListError, InvalidRevocationListError } from '../errors'\nimport { IdentifierListCwtProtectedHeaders, MdocMediaTypes } from './identifier-list-cwt-headers'\nimport {\n type CreateIdentifierListCwtPayloadOptions,\n IdentifierListCwtClaimKey,\n IdentifierListCwtPayload,\n} from './identifier-list-cwt-payload'\n\n/** The default maximum size of an identifier list response, as of a status list response. */\nconst DEFAULT_MAX_RESPONSE_BYTES = 16 * 1024 * 1024\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, MdocMediaTypes.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 CoseValidationError (from `@owf/cose`) 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`, in a response within the `identifierList` limit of\n * `ctx.fetchLimits`, 16 MiB by default.\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 * @throws InvalidRevocationListError if the response is not an identifier list, or larger than its limit.\n */\n public static async fetch(uri: string, ctx: Pick<MdocContext, 'fetch' | 'fetchLimits'>): Promise<IdentifierListCwt> {\n let response: Response\n try {\n response = await fetchWithLimits(ctx, {\n type: 'identifierList',\n url: uri,\n accept: MdocMediaTypes.IdentifierListCwt,\n defaultMaxResponseBytes: DEFAULT_MAX_RESPONSE_BYTES,\n })\n } catch (error) {\n if (!(error instanceof IdentityCommonError)) throw error\n throw new InvalidRevocationListError(`Identifier list at ${uri}: ${error.message}`)\n }\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, MdocMediaTypes.IdentifierListCwt)) {\n throw new InvalidRevocationListError(\n `Identifier list at ${uri} was served as '${contentType}', expected '${MdocMediaTypes.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 CoseX5ChainNotBoundError,\n getIntegrityProtectedX5Chain,\n RegisteredCwtClaimKey,\n SignatureAlgorithm,\n} from '@owf/cose'\nimport { base64, base64url } from '@owf/identity-common'\nimport {\n fetchStatusList,\n JoseError,\n JoseSignatureVerificationError,\n JoseValidationError,\n type StatusList,\n StatusListCwt,\n StatusListError,\n type StatusListInfo,\n type StatusListJwtPayload,\n StatusListValidationError,\n StatusType,\n type VerifyStatusListJwtOptions,\n verifyStatusListJwt as verifyTokenStatusListJwt,\n} from '@owf/token-status-list'\nimport type { MdocContext } from '../../context'\nimport {\n InvalidIdentifierListSignatureError,\n InvalidRevocationListError,\n InvalidSignatureError,\n type MdlError,\n NoPublicKeySetOnStatusListError,\n StatusListEntryNotValidError,\n TrustedRevocationCertificatesMustContainAtleastOneCertificateError,\n UnableToExtractX5ChainFromCwtError,\n UnableToExtractX5ChainFromIdentifierListError,\n UnableToExtractX5ChainFromJwtError,\n UnprotectedX5ChainNotBoundError,\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<T>(\n verification: () => Promise<T> | T,\n /** The error to report a failed signature as. */\n invalidSignatureError: new (message: string) => MdlError\n): Promise<T> {\n try {\n return await verification()\n } catch (error) {\n if (error instanceof CoseInvalidSignatureError) throw new invalidSignatureError(error.message)\n if (error instanceof CoseX5ChainNotBoundError) throw new UnprotectedX5ChainNotBoundError(error.message)\n // The cause is what the verification callback threw, already an mdoc error\n if (error instanceof JoseSignatureVerificationError) throw error.cause ?? new invalidSignatureError(error.message)\n if (\n error instanceof StatusListError ||\n error instanceof StatusListValidationError ||\n error instanceof JoseError ||\n error instanceof JoseValidationError\n ) {\n throw new InvalidRevocationListError(error.message)\n }\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\". A status list may instead carry it in the\n * unprotected header when a protected `x5t` binds its leaf, as RFC 9360 allows.\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\n/**\n * The JWS algorithms a status list in JWT format may be signed with: ECDSA only, whose raw `r||s`\n * signature is the same in JWS and COSE, with the length of that signature (RFC 7518 § 3.4). `none`\n * and HMAC are refused, as an HMAC keyed with the public key of the certificate would be accepted\n * from anyone.\n */\ntype JwsSignatureAlgorithm = { algorithm: SignatureAlgorithm; signatureLength: number }\nconst jwsSignatureAlgorithms = new Map<string, JwsSignatureAlgorithm>([\n ['ES256', { algorithm: SignatureAlgorithm.ES256, signatureLength: 64 }],\n ['ES384', { algorithm: SignatureAlgorithm.ES384, signatureLength: 96 }],\n ['ES512', { algorithm: SignatureAlgorithm.ES512, signatureLength: 132 }],\n])\n\n/**\n * Checks the status at `idx`, only once the list verified, so that a list that does not verify is never\n * reported as a status (Token Status List § 8.3). § 12.3.6.1 accepts no status but Valid.\n */\nasync function assertStatusValid(statusList: StatusList, uri: string, idx: number) {\n const status = await asMdlRevocationListError(() => statusList.getStatus(idx), InvalidSignatureError)\n if (status !== StatusType.Valid) {\n throw new StatusListEntryNotValidError(\n `Status for id '${idx}' is not Valid (${StatusType.Valid}), but is instead '${status}'`,\n { uri, idx, status }\n )\n }\n}\n\n/**\n * Verify a status list in JWT format to the same rules as a CWT, with `verifyStatusListJwt` of\n * `@owf/token-status-list` and a callback that validates the `x5c` chain and checks the signature\n * with the `MdocContext`.\n */\nasync function verifyStatusListJwt(\n {\n jwt,\n uri,\n idx,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n skewSeconds,\n checkFreshness,\n maxDecompressedBytes,\n }: { jwt: string; uri: string; idx: number; now: Date } & Omit<\n VerifyStatusListTokenOptions,\n 'statusListInfo' | 'now'\n >,\n ctx: Pick<MdocContext, 'x509' | 'cose'>\n) {\n let chain: Array<Uint8Array> | undefined\n const verifyJwsCallback: VerifyStatusListJwtOptions['verifyJwsCallback'] = async (\n signer,\n { signingInputBytes, signature }\n ) => {\n if (signer.method !== 'x5c') throw new UnableToExtractX5ChainFromJwtError()\n // Set, as `allowedAlgorithms` only has the keys of the map\n const { algorithm, signatureLength } = jwsSignatureAlgorithms.get(signer.alg) as JwsSignatureAlgorithm\n\n const signerKey = await verifyRevocationListSigner(\n {\n // RFC 7515 § 4.1.6: standard base64 DER, not base64url.\n x5chain: signer.x5c.map((cert) => base64.decode(cert)),\n algorithm,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n },\n ctx\n )\n chain = signerKey.chain\n\n // A DER-encoded signature, as some signers produce, is not a JWS signature and is rejected here\n // rather than left to the `sign1.verify` callback, which may throw on an unexpected length.\n const signatureBytes = base64url.decode(signature)\n if (signatureBytes.length !== signatureLength) {\n throw new InvalidSignatureError(\n `The signature of the status list at ${uri} is ${signatureBytes.length} bytes, not the ${signatureLength} bytes of a raw ${signer.alg} signature`\n )\n }\n\n const verified = await ctx.cose.sign1.verify({\n toBeVerified: signingInputBytes,\n signature: signatureBytes,\n key: signerKey.key,\n algorithm,\n })\n if (!verified) throw new InvalidSignatureError(`The signature of the status list at ${uri} is not valid`)\n return { verified: true, signerJwk: signerKey.key.jwk as { kty: string } }\n }\n\n const { header, payload, statusList } = await asMdlRevocationListError(\n () =>\n verifyTokenStatusListJwt({\n jwt,\n uri,\n now,\n skewSeconds,\n checkIssuedAt: checkFreshness,\n // § 12.3.6.3: \"The exp claim shall be present.\"\n requiredClaims: ['exp'],\n allowedAlgorithms: [...jwsSignatureAlgorithms.keys()],\n verifyJwsCallback,\n maxDecompressedBytes,\n }),\n InvalidSignatureError\n )\n\n await assertStatusValid(statusList, uri, idx)\n\n return { statusListJwt: { header, payload, statusList }, chain }\n}\n\n/**\n * How the verification of an mdoc checks the status list and identifier list of its MSO\n * (ISO/IEC 18013-5 second edition § 12.3.6).\n */\nexport type StatusVerificationOptions = {\n /** Don't fetch and check the status list or identifier list of the MSO. */\n disableValidation?: boolean\n /** The maximum size in bytes the status list may inflate to, 16 MiB by default. */\n maxDecompressedBytes?: number\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 /** The maximum size in bytes the status list may inflate to, 16 MiB by default. */\n maxDecompressedBytes?: number\n}\n\n/** A status list served in JWT format, once verified. */\nexport type VerifiedStatusListJwt = {\n header: Record<string, unknown>\n payload: StatusListJwtPayload\n statusList: StatusList\n}\n\nexport type VerifyStatusListTokenResult = {\n /** The verified list, when it was served in CWT format. */\n statusListCwt?: StatusListCwt\n /** The verified list, when it was served in JWT format instead. */\n statusListJwt?: VerifiedStatusListJwt\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 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 CWT is preferred. A list served as a JWT is still accepted as a fallback,\n * verified to the same rules; the JWS checks (ECDSA only, no `crit`, the `x5c` signer chain) live\n * in `verifyStatusListJwt`.\n *\n * The signer chain of a CWT is read from the protected header, as § 12.3.6.3 requires, or else from\n * the unprotected header when a protected `x5t` matches its leaf (RFC 9360).\n */\nexport async function verifyStatusListToken(\n {\n statusListInfo,\n trustedCertificates,\n disableCertificateChainValidation,\n now = new Date(),\n skewSeconds,\n checkFreshness,\n maxDecompressedBytes,\n }: VerifyStatusListTokenOptions,\n ctx: Pick<MdocContext, 'fetch' | 'fetchLimits' | 'x509' | 'cose' | 'crypto'>\n): Promise<VerifyStatusListTokenResult> {\n if (!disableCertificateChainValidation) assertTrustedCertificates({ trustedCertificates })\n\n const { uri, idx } = statusListInfo\n // CWT is preferred, so that an issuer that serves both returns the format § 12.3.6.3 requires. The\n // JWT is asked for with a lower quality value, and still accepted if a server returns it anyway.\n const token = await fetchStatusList({\n uri,\n customFetcher: ctx.fetch,\n fetchLimits: ctx.fetchLimits,\n acceptedFormats: ['cwt', 'jwt'],\n })\n\n // NOTE: a JWT is NOT allowed by § 12.3.6.3, but some issuers serve the status list of an mdoc\n // as JWT only. So it is accepted as a fallback, with the same checks and status handling as a CWT.\n if (typeof token === 'string') {\n const { statusListJwt, chain } = await verifyStatusListJwt(\n {\n jwt: token,\n uri,\n idx,\n trustedCertificates,\n disableCertificateChainValidation,\n now,\n skewSeconds,\n checkFreshness,\n maxDecompressedBytes,\n },\n ctx\n )\n\n return { statusListJwt, chain }\n }\n\n const statusListCwt = StatusListCwt.fromToken(token)\n\n // NOTE: an unprotected x5chain is NOT allowed by § 12.3.6.3, but RFC 9360 allows it when a\n // protected x5t binds the leaf. So it is accepted with that binding.\n const x5chain = await asMdlRevocationListError(\n () => getIntegrityProtectedX5Chain(statusListCwt, ctx.crypto),\n InvalidSignatureError\n )\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 and claims first: the token is only the issuer's if it verifies, so there is nothing\n // to read from it before that.\n await asMdlRevocationListError(\n () =>\n statusListCwt.verify(\n {\n key,\n uri,\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 const statusList = await asMdlRevocationListError(\n () => statusListCwt.payload.getStatusList({ maxDecompressedBytes }),\n InvalidSignatureError\n )\n await assertStatusValid(statusList, uri, idx)\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' | 'fetchLimits' | '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","import {\n CosePayloadMustBeDefinedError,\n cborDecode,\n DataItem,\n Sign1,\n type Sign1EncodedStructure,\n type Sign1Options,\n verifyX5t,\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 {\n defaultVerificationCallback,\n onCategoryCheck,\n type VerificationAssessmentResult,\n type VerificationCallback,\n} from '../check-callback.js'\nimport { IdentifierFoundInRevokedListError, StatusListEntryNotValidError } from '../errors.js'\nimport type { IdentifierListCwt } from './identifier-list-cwt'\nimport { MobileSecurityObject, type MobileSecurityObjectEncodedStructure } from './mobile-security-object.js'\nimport { type StatusVerificationOptions, 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 /**\n * Only a status list served in CWT format is returned here. One served as a JWT is verified but\n * leaves this unset; `trustedStatusListChain` is set for either when its chain was validated.\n */\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 revocation list that fails verification; succeeds silently otherwise.\n *\n * It fetches the revocation list URIs of the MSO, so call it only once the issuer is trusted: the\n * URIs of a self-signed MSO are chosen by whoever presents it. `verify` does not check the status\n * without certificate chain validation, and leaves it to this method.\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 maxDecompressedBytes,\n }: Omit<StatusVerificationOptions, 'disableValidation'> & {\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' | 'fetchLimits' | 'x509' | 'cose' | 'crypto'>\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 maxDecompressedBytes,\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 /**\n * The revocation of the mdoc as data, when `error` reports one, so that a caller can tell it from\n * a revocation list that could not be verified without parsing the message.\n */\n private revocationResult(error: unknown): VerificationAssessmentResult | undefined {\n if (error instanceof StatusListEntryNotValidError) {\n const { uri, idx, status } = error\n return { type: 'statusListEntryNotValid', uri, idx, status }\n }\n\n const identifierList = this.mobileSecurityObject.status?.identifierList\n if (error instanceof IdentifierFoundInRevokedListError && identifierList) {\n return { type: 'identifierListEntryRevoked', uri: identifierList.uri, id: identifierList.id }\n }\n\n return undefined\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 skewSeconds?: number\n status?: StatusVerificationOptions\n },\n ctx: Pick<MdocContext, 'x509' | 'cose' | 'fetch' | 'fetchLimits' | 'crypto'>\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.status?.disableValidation ?? 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 // ISO/IEC 18013-5 (second edition) § 12.3.4: an x5t, if present, shall use SHA-256. The x5chain\n // stays in the unprotected header without one, as the first edition requires.\n const x5tCheck = 'The x5t in the protected header, if present, must be SHA-256 and match the issuer certificate'\n try {\n await verifyX5t(this, this.certificate, ctx.crypto)\n onCheck({ status: 'PASSED', check: x5tCheck })\n } catch (err) {\n onCheck({ status: 'FAILED', check: x5tCheck, reason: err instanceof Error ? err.message : 'Unknown error' })\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 a trusted issuer. A forged MSO must not make the verifier request a URI of its choosing.\n // Without chain validation, the signature only shows that the MSO is signed with the key of its own\n // certificate, so the status is left to `verifyStatus` once the caller trusts the issuer.\n if (!disableStatusValidation && isSignatureValid && disableCertificateChainValidation) {\n onCheck({\n status: 'WARNING',\n check: 'Status information must be valid',\n reason:\n 'The status is not checked without certificate chain validation. Call IssuerAuth.verifyStatus once the issuer is trusted.',\n })\n } else if (!disableStatusValidation && isSignatureValid) {\n try {\n ;({ statusList, trustedStatusListChain, identifierList, trustedIdentifierListChain } = await this.verifyStatus(\n {\n now,\n skewSeconds,\n checkFreshness: true,\n trustedStatusCertificates,\n maxDecompressedBytes: options.status?.maxDecompressedBytes,\n },\n ctx\n ))\n } catch (err) {\n // The default callback throws the reason without the check, so the reason names the lists.\n const { statusList: statusListInfo, identifierList: identifierListInfo } =\n this.mobileSecurityObject.status ?? {}\n const lists = [\n statusListInfo && `status list ${statusListInfo.uri}`,\n identifierListInfo && `identifier list ${identifierListInfo.uri}`,\n ]\n .filter(Boolean)\n .join(' and ')\n onCheck({\n status: 'FAILED',\n check: 'Status information must be valid',\n reason: `Verifying the ${lists} failed: ${err instanceof Error ? err.message : 'Unknown error'}`,\n result: this.revocationResult(err),\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 zIssuerSignedItem = typedMap([\n ['digestID', z.number()],\n ['random', zUint8Array],\n ['elementIdentifier', z.string()],\n ['elementValue', z.unknown()],\n])\n\nexport type IssuerSignedItemEncodedStructure = z.input<typeof zIssuerSignedItem>\nexport type IssuerSignedItemDecodedStructure = z.output<typeof zIssuerSignedItem>\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 zIssuerSignedItem\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 zIssuerNamespacesEncoded = z.map(z.string(), z.array(z.instanceof(DataItem)))\nexport const zIssuerNamespacesDecoded = z.map(z.string(), z.array(z.instanceof(IssuerSignedItem)))\n\nexport type IssuerNamespacesEncodedStructure = z.infer<typeof zIssuerNamespacesEncoded>\nexport type IssuerNamespacesDecodedStructure = z.infer<typeof zIssuerNamespacesDecoded>\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(zIssuerNamespacesEncoded, zIssuerNamespacesDecoded, {\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 { StatusVerificationOptions } from './mso-revocation-list'\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 zIssuerSigned = typedMap([\n ['nameSpaces', z.instanceof(IssuerNamespaces).exactOptional()],\n ['issuerAuth', z.instanceof(IssuerAuth)],\n])\n\nexport type IssuerSignedDecodedStructure = z.output<typeof zIssuerSigned>\nexport type IssuerSignedEncodedStructure = z.input<typeof zIssuerSigned>\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(zIssuerSigned.in, zIssuerSigned.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 skewSeconds?: number\n status?: StatusVerificationOptions\n },\n ctx: Pick<MdocContext, 'x509' | 'crypto' | 'cose' | 'fetch' | 'fetchLimits'>\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","/**\n * A doc request, with the documents of the response that may answer it.\n */\nexport type DocRequestCandidates = {\n docRequestIndex: number\n uniqueDocSetRequired: boolean\n /**\n * The documents of its docType and of an issuer it accepts, which may answer it with elements left\n * out, as a holder can decline them.\n */\n candidateDocuments: Array<number>\n /**\n * The candidate documents that satisfy it.\n */\n validDocuments: Array<number>\n}\n\n/**\n * Works out which document answers which doc request, as a response does not say.\n *\n * A doc request without `uniqueDocSetRequired` is answered by every candidate document. One with it\n * is answered by one document only, and a document can answer several doc requests. A document that\n * only doc requests with `uniqueDocSetRequired` may answer therefore needs one of them to itself: when\n * there are more such documents than doc requests to take them, the response has documents too many,\n * and those doc requests fail (`excess`). They are found with a maximum matching, and are the same\n * whatever the order of the documents (the deficient part of the Dulmage-Mendelsohn decomposition).\n *\n * The other doc requests can be answered together (`canAnswer`) when the documents can be shared\n * out so that each of them with `uniqueDocSetRequired` gets one that satisfies it, while each of\n * those documents still has a doc request of its own.\n */\nexport const createAttribution = (docRequests: Array<DocRequestCandidates>) => {\n const byIndex = new Map(docRequests.map((docRequest) => [docRequest.docRequestIndex, docRequest]))\n const satisfying = new Map(\n docRequests.map((docRequest) => [docRequest.docRequestIndex, new Set(docRequest.validDocuments)])\n )\n\n // The documents that only doc requests with `uniqueDocSetRequired` may answer.\n const candidatesOf = new Map<number, Array<number>>()\n for (const { docRequestIndex, candidateDocuments } of docRequests) {\n for (const documentIndex of candidateDocuments) {\n candidatesOf.set(documentIndex, [...(candidatesOf.get(documentIndex) ?? []), docRequestIndex])\n }\n }\n const onlyUnique = Array.from(candidatesOf)\n .filter(([, docRequestIndexes]) => docRequestIndexes.every((index) => byIndex.get(index)?.uniqueDocSetRequired))\n .map(([documentIndex]) => documentIndex)\n .sort((a, b) => a - b)\n const excess = findExcess(\n onlyUnique,\n candidatesOf,\n maximumMatching(onlyUnique, (documentIndex) => candidatesOf.get(documentIndex) ?? [])\n )\n const excessDocRequests = new Set(excess.docRequestIndexes)\n const excessDocuments = new Set(excess.documentIndexes)\n const remaining = onlyUnique.filter((documentIndex) => !excessDocuments.has(documentIndex))\n\n /**\n * A doc request per remaining document, where each doc request of `required` with\n * `uniqueDocSetRequired` only takes a document that satisfies it. Undefined when there is none.\n */\n const shareOut = (required: ReadonlySet<number>) => {\n const neighbours = (documentIndex: number) =>\n // A doc request in `excess` already fails, and does not take another document.\n (candidatesOf.get(documentIndex) ?? []).filter(\n (docRequestIndex) =>\n !excessDocRequests.has(docRequestIndex) &&\n (!required.has(docRequestIndex) || (satisfying.get(docRequestIndex)?.has(documentIndex) ?? false))\n )\n const taken = maximumMatching(remaining, neighbours)\n return taken.size === remaining.length ? taken : undefined\n }\n\n /**\n * Whether the doc requests can be answered together: each satisfied by a document, and those with\n * `uniqueDocSetRequired` by a document they can have to themselves when they need one.\n */\n const answers = new Map<string, boolean>()\n const canAnswer = (docRequestIndexes: Array<number>) => {\n const required = new Set(docRequestIndexes)\n const key = Array.from(required)\n .sort((a, b) => a - b)\n .join(',')\n const known = answers.get(key)\n if (known !== undefined) return known\n const answer = canAnswerUncached(required)\n answers.set(key, answer)\n return answer\n }\n const canAnswerUncached = (required: ReadonlySet<number>) => {\n for (const docRequestIndex of required) {\n const docRequest = byIndex.get(docRequestIndex)\n if (!docRequest || docRequest.validDocuments.length === 0 || excessDocRequests.has(docRequestIndex)) return false\n }\n return shareOut(required) !== undefined\n }\n\n /**\n * Per doc request, the documents it answers when `docRequestIndexes` are answered together.\n */\n const answer = (docRequestIndexes: Array<number>) => {\n const required = new Set(docRequestIndexes)\n const taken = shareOut(required) ?? new Map<number, number>()\n const takes = new Map(Array.from(taken, ([documentIndex, docRequestIndex]) => [docRequestIndex, documentIndex]))\n\n const byDocRequest = new Map<number, Array<number>>()\n for (const docRequest of docRequests) {\n const { docRequestIndex, uniqueDocSetRequired, candidateDocuments, validDocuments } = docRequest\n if (!uniqueDocSetRequired) {\n byDocRequest.set(docRequestIndex, candidateDocuments)\n continue\n }\n if (excessDocRequests.has(docRequestIndex)) {\n byDocRequest.set(docRequestIndex, [])\n continue\n }\n // A document of its own, or else one it shares with another doc request.\n const documentIndex = takes.get(docRequestIndex) ?? validDocuments[0]\n byDocRequest.set(docRequestIndex, documentIndex === undefined ? [] : [documentIndex])\n }\n return byDocRequest\n }\n\n return { excess, canAnswer, answer }\n}\n\n/**\n * A maximum matching of `documents` to doc requests (Kuhn's algorithm), as the doc request each\n * matched document takes. O(documents · edges).\n */\nconst maximumMatching = (documents: Array<number>, neighbours: (documentIndex: number) => Array<number>) => {\n const takenBy = new Map<number, number>()\n const augment = (documentIndex: number, visited: Set<number>): boolean => {\n // A free doc request first, so that documents only move when they have to.\n const free = neighbours(documentIndex).find((docRequestIndex) => !takenBy.has(docRequestIndex))\n if (free !== undefined) {\n takenBy.set(free, documentIndex)\n return true\n }\n for (const docRequestIndex of neighbours(documentIndex)) {\n if (visited.has(docRequestIndex)) continue\n visited.add(docRequestIndex)\n const current = takenBy.get(docRequestIndex)\n if (current !== undefined && augment(current, visited)) {\n takenBy.set(docRequestIndex, documentIndex)\n return true\n }\n }\n return false\n }\n for (const documentIndex of documents) augment(documentIndex, new Set())\n\n return new Map(Array.from(takenBy, ([docRequestIndex, documentIndex]) => [documentIndex, docRequestIndex]))\n}\n\n/**\n * The documents left without a doc request in a maximum matching, with every document an alternating\n * path reaches from them: along a candidate of a document, and back along the document that doc\n * request takes. These are the documents some maximum matching leaves without a doc request, and\n * their candidates are the doc requests with documents too many.\n */\nconst findExcess = (\n documents: Array<number>,\n candidatesOf: Map<number, Array<number>>,\n matching: Map<number, number>\n) => {\n const takes = new Map(Array.from(matching, ([documentIndex, docRequestIndex]) => [docRequestIndex, documentIndex]))\n\n const queue = documents.filter((documentIndex) => !matching.has(documentIndex))\n const reached = new Set(queue)\n for (let position = 0; position < queue.length; position++) {\n for (const docRequestIndex of candidatesOf.get(queue[position] as number) ?? []) {\n const next = takes.get(docRequestIndex)\n if (next !== undefined && !reached.has(next)) {\n reached.add(next)\n queue.push(next)\n }\n }\n }\n\n const documentIndexes = Array.from(reached).sort((a, b) => a - b)\n const docRequestIndexes = new Set(documentIndexes.flatMap((documentIndex) => candidatesOf.get(documentIndex) ?? []))\n return { documentIndexes, docRequestIndexes: Array.from(docRequestIndexes).sort((a, b) => a - b) }\n}\n","import { hexEncode } from '@owf/identity-common'\nimport { parseCertificate } from '@owf/x509'\nimport type { VerificationCallback } from '../mdoc/check-callback'\nimport { InvalidDeviceRequestMatchOptionsError } from '../mdoc/errors'\nimport type { AlternativeDataElementsSet } from '../mdoc/models/alternative-data-elements-set'\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 {\n describeAgeOverLimitViolations,\n findAgeOverCandidate,\n findAgeOverLimitViolations,\n findAgeOverRequestLimitViolations,\n} from './ageOver'\nimport { createAttribution } from './attribution'\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 and no use cases does not say whether it asks\n * for all of them, or for any one of them. ISO/IEC TS 23220-4 7.2.1.3.2 reads it as all of them,\n * which is the default: a single mandatory use case whose document set holds every doc request.\n * Set this to treat them as alternatives instead, one optional use case per doc request, of which\n * at least one has to be satisfied. That is how the iOS DC API presents such a request.\n *\n * A device request that carries use cases (ISO/IEC TS 23220-4 7.2.1.3.4, taken up by the second\n * edition of 18013-5) is matched by them, and this option does not apply. Neither does it to a\n * 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 * Set when the doc request has alternatives for the element (ISO/IEC TS 23220-4 7.2.1.3.2): every\n * way it can be answered, in order of preference. The element itself comes first when it is\n * there, then each alternative set whose elements all are, in the reader's order, possibly in other\n * namespaces (18013-5 second edition 10.2.4).\n *\n * `disclosedElementIdentifier`, `elementValue` and `source` describe the first element of the first\n * option. That option is an alternative set (it has an `alternativeElementSetIndex`) only when the\n * element itself is not there. A holder discloses an alternative set by choosing it with the\n * `alternatives` of the document it creates, and otherwise the element itself.\n */\n options?: NonEmptyArray<ClaimMatchOption>\n}\n\n/**\n * One way to answer a requested element that has alternatives (ISO/IEC TS 23220-4 7.2.1.3.2): the\n * element itself, or every element of one of its alternative sets (18013-5 second edition 10.2.4).\n */\nexport type ClaimMatchOption = {\n /**\n * Index into the `alternativeElementSets` of the element, when the option is one of them rather\n * than the element itself.\n */\n alternativeElementSetIndex?: number\n elements: NonEmptyArray<DisclosedElement>\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\nexport type IssuerMatchSuccess = { success: true }\nexport type IssuerMatchFailure = { success: false; reason: string }\n\n/**\n * Whether a document or credential comes from an issuer the doc request accepts: a certificate in\n * its certificate chain has one of the `issuerIdentifiers` of the `requestInfo` of the doc request\n * as its authority key identifier (ISO/IEC TS 23220-4 7.2.1.3.2, 18013-5 second edition 10.2.4).\n * Only present when the doc request names issuers.\n */\nexport type IssuerMatchResult = IssuerMatchSuccess | IssuerMatchFailure\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 issuer?: IssuerMatchSuccess\n claims: DocumentClaimsMatchSuccess\n}\n\nexport type DocumentMatchFailure = DocumentMatchBase & {\n success: false\n docType: DocTypeMatchResult\n issuer?: IssuerMatchResult\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 /**\n * Empty, unless the doc request requires a unique document set that the response does not give,\n * see `reason`.\n */\n validDocuments: Array<DocumentMatchSuccess>\n /**\n * Set when the `requestInfo` of the doc request sets `uniqueDocSetRequired` (ISO/IEC TS 23220-4\n * 7.2.1.3.2), and the response has more documents for it than one: documents of its docType and\n * of an issuer it accepts, satisfying it or not, that may only answer doc requests that take one\n * document each, this one among them, and outnumber them; or when such documents leave it none\n * that satisfies it. See {@link DeviceRequestAttribution}.\n */\n reason?: string\n}\n\nexport type DocRequestMatch = DocRequestMatchSuccess | DocRequestMatchFailure\n\n/**\n * How a use case is satisfied.\n */\nexport type UseCaseMatch = {\n /**\n * Index into `useCases` of the use case this result is about, which for use cases of the device\n * request is also their index into `deviceRequestInfo.useCases`.\n */\n useCaseIndex: number\n mandatory: boolean\n /**\n * The purpose hints of the use case, to tell the user what each use case is for (18013-5 second\n * edition 10.2.5). Only use cases of the `deviceRequestInfo` have them.\n */\n purposeHints?: Map<string, number>\n /**\n * Whether the use case can be answered on its own. Whether it can be answered together with the\n * others is in `attribution` of the match.\n */\n success: boolean\n /**\n * Every document set of the use case, in request order: the doc requests, by index, that answer\n * it together.\n */\n documentSets: Array<Array<number>>\n /**\n * The document sets of `documentSets` whose doc requests are all satisfied, in request order.\n * Empty when none is. A holder answers exactly one of them (ISO/IEC TS 23220-4 7.2.1.4).\n */\n matchingDocumentSets: Array<Array<number>>\n}\n\n/**\n * Where the use cases of a match come from.\n *\n * `'deviceRequestInfo'`: the use cases of the `deviceRequestInfo` of the device request (ISO/IEC TS\n * 23220-4 7.2.1.3.4).\n *\n * `'allDocRequests'`: the device request carries none, so every doc request is requested (7.2.1.3.2):\n * a single mandatory use case, whose one document set holds every doc request.\n *\n * `'eachDocRequest'`: the device request carries none, and\n * `treatAmbiguousMultipleDocRequestsAsAlternatives` is set: one optional use case per doc request.\n */\nexport type UseCasesSource = 'deviceRequestInfo' | 'allDocRequests' | 'eachDocRequest'\n\nexport type UseCasesMatch = {\n useCasesSource: UseCasesSource\n /**\n * One entry per use case, in order. The match succeeds when every mandatory use case is satisfied\n * and at least one use case is (18013-5 second edition 10.2.5).\n */\n useCases: Array<UseCaseMatch>\n}\n\n/**\n * Which document answers which doc request, and with which document set each use case is answered.\n * A response does not say, so the match works it out. A document may answer every doc request of\n * its docType and of an issuer it accepts, also with elements left out, as a holder can decline\n * them, and one document can answer several doc requests. A doc request with `uniqueDocSetRequired`\n * takes one document only, so a document that only such doc requests may answer needs one of them\n * to itself, and they are only satisfied together when that leaves each of them a document that\n * satisfies it. Whether they are does not depend on the order of the documents; which document a\n * doc request takes, when several would do, may.\n *\n * A holder answers each use case with exactly one document set (ISO/IEC TS 23220-4 7.2.1.4), so a\n * document that answers no doc request of the sets in `useCases`, nor of a use case that is not\n * satisfied, should not have been sent, which `reportDeviceRequestMatch` warns about.\n */\nexport type DeviceRequestAttribution = {\n /**\n * The use cases the response is taken to answer, in order, each with its document set: every\n * mandatory use case, and the others that can be answered together with them, tried in order. Of\n * the `matchingDocumentSets` of a use case, the set the most documents may answer is tried first,\n * then request order.\n */\n useCases: Array<{ useCaseIndex: number; documentSet: Array<number> }>\n /**\n * Per document, in response order, the doc requests it answers, in order. Empty for a document\n * that answers none.\n */\n documents: Array<{ documentIndex: number; docRequestIndexes: Array<number> }>\n}\n\ntype DeviceRequestMatchBase = UseCasesMatch & {\n /**\n * Documents in the response whose docType no doc request asked for.\n */\n unrequestedDocuments: Array<{ documentIndex: number; docType: DocType }>\n attribution: DeviceRequestAttribution\n}\n\n/**\n * Every mandatory use case is satisfied, and at least one use case is.\n */\nexport type DeviceRequestMatchSuccess = DeviceRequestMatchBase &\n (\n | {\n success: true\n useCasesSource: 'allDocRequests'\n /**\n * One entry per doc request, in request order. All of them are successful.\n */\n docRequests: Array<DocRequestMatchSuccess>\n }\n | {\n success: true\n useCasesSource: 'deviceRequestInfo' | 'eachDocRequest'\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<DocRequestMatch>\n }\n )\n\nexport type DeviceRequestMatchFailure = DeviceRequestMatchBase & {\n success: false\n /**\n * Set when every use case the response has to satisfy can be satisfied on its own, or every doc\n * request when they are all requested, but not together, see {@link DeviceRequestAttribution}.\n */\n reason?: string\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 issuer?: IssuerMatchSuccess\n claims: ClaimsMatchSuccess\n}\n\nexport type CredentialMatchFailure = CredentialMatchBase & {\n success: false\n docType: DocTypeMatchResult\n issuer?: IssuerMatchResult\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 mandatory use case can be satisfied, and at least one use case can.\n */\nexport type HolderDeviceRequestMatchSuccess = UseCasesMatch &\n (\n | {\n success: true\n useCasesSource: 'allDocRequests'\n /**\n * One entry per doc request, in request order. All of them are successful.\n */\n docRequests: Array<HolderDocRequestMatchSuccess>\n }\n | {\n success: true\n useCasesSource: 'deviceRequestInfo' | 'eachDocRequest'\n /**\n * One entry per doc request, in request order.\n */\n docRequests: Array<HolderDocRequestMatch>\n }\n )\n\nexport type HolderDeviceRequestMatchFailure = UseCasesMatch & {\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 * The doc requests are matched by use case: those of the device request (ISO/IEC TS 23220-4\n * 7.2.1.3.4) when it carries them, and otherwise every doc request as one mandatory use case, or each\n * doc request as an optional one when `treatAmbiguousMultipleDocRequestsAsAlternatives` is set in\n * `matchOptions`. The match succeeds when every mandatory use case is satisfied and at least one is.\n *\n * The `requestInfo` of a doc request is applied too: a document of an issuer it does not name\n * fails, an alternative set it allows answers a requested element, and its elements count as\n * requested rather than over-disclosed, and with\n * `uniqueDocSetRequired` the doc request fails when the response has more documents for it than\n * one, see {@link DeviceRequestAttribution} for which document answers which doc request.\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 /**\n * Per document, in response order, its certificate chain as validated against the trusted\n * certificates, leaf first. The `issuerIdentifiers` of a doc request are matched against it, and\n * a document without one does not satisfy a doc request that names issuers. The x5chain is not\n * used: it is in the unprotected header of the IssuerAuth, so a holder can add the certificate of\n * any issuer to it. `Verifier.verifyDeviceResponse` passes the chains it validates.\n */\n issuerCertificateChains?: Array<Array<Uint8Array> | undefined>\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 matches = deviceRequest.docRequests.map((docRequest, docRequestIndex) => {\n const { docType, namespaces, requestInfo } = 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 issuerResult = matchIssuer(\n requestInfo?.issuerIdentifiers,\n options.issuerCertificateChains?.[documentIndex],\n 'validated certificate chain'\n )\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 alternatives: requestInfo?.alternativeDataElements,\n })\n const claimsResult: DocumentClaimsMatchResult = {\n ...toClaimsMatchResult(claims),\n unrequestedClaims: unusedElements,\n }\n\n const issuer = issuerResult ? { issuer: issuerResult } : {}\n return docTypeResult.success && claimsResult.success && issuerResult?.success !== false\n ? {\n documentIndex,\n success: true,\n docType: docTypeResult,\n ...(issuer as { issuer?: IssuerMatchSuccess }),\n claims: claimsResult,\n }\n : { documentIndex, success: false, docType: docTypeResult, ...issuer, claims: claimsResult }\n })\n\n return {\n docRequestIndex,\n docType,\n uniqueDocSetRequired: requestInfo?.uniqueDocSetRequired ?? false,\n // A document of its docType and of an issuer it accepts may answer it with elements left out.\n candidateDocuments: documentMatches.filter(\n (documentMatch) => documentMatch.docType.success && documentMatch.issuer?.success !== false\n ),\n validDocuments: documentMatches.filter((documentMatch) => documentMatch.success),\n failedDocuments: documentMatches.filter((documentMatch) => !documentMatch.success),\n }\n })\n\n const attribution = createAttribution(\n matches.map(({ docRequestIndex, uniqueDocSetRequired, candidateDocuments, validDocuments }) => ({\n docRequestIndex,\n uniqueDocSetRequired,\n candidateDocuments: candidateDocuments.map((document) => document.documentIndex),\n validDocuments: validDocuments.map((document) => document.documentIndex),\n }))\n )\n const excessDocuments = new Set(attribution.excess.documentIndexes)\n\n const docRequests = matches.map(({ uniqueDocSetRequired, candidateDocuments, ...match }): DocRequestMatch => {\n const { docRequestIndex, docType, validDocuments, failedDocuments } = match\n const failure = (reason: string): DocRequestMatchFailure => ({\n docRequestIndex,\n docType,\n success: false,\n validDocuments,\n failedDocuments,\n reason,\n })\n\n // More documents than doc requests that take one document each can take, this one among them.\n const excess = uniqueDocSetRequired\n ? candidateDocuments\n .map((document) => document.documentIndex)\n .filter((documentIndex) => excessDocuments.has(documentIndex))\n : []\n if (excess.length > 0) {\n const own = new Set(excess)\n const others = matches\n .filter((other) => other.candidateDocuments.some((document) => own.has(document.documentIndex)))\n .map((other) => other.docRequestIndex)\n return failure(\n `Doc request ${docRequestIndex} requires a unique document set, but the response has more documents than such doc requests can take: documents ${excess.join(', ')} may only answer ${others.length === 1 ? `doc request ${docRequestIndex}` : `doc requests ${others.join(', ')}, which all do`}`\n )\n }\n if (uniqueDocSetRequired && isNonEmptyArray(validDocuments) && !attribution.canAnswer([docRequestIndex])) {\n return failure(\n `Doc request ${docRequestIndex} requires a unique document set, and the documents that only doc requests like it may answer leave it none of documents ${validDocuments.map((document) => document.documentIndex).join(', ')}, which satisfy it`\n )\n }\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 const useCases = matchUseCases(\n resolveUseCases(deviceRequest, matchOptions?.treatAmbiguousMultipleDocRequestsAsAlternatives),\n docRequests,\n attribution.canAnswer\n )\n\n // Which document set each use case is answered with: of a use case, the set the most documents\n // may answer is tried first.\n const documentsOf = (documentSet: Array<number>) =>\n new Set(\n documentSet.flatMap((index) => matches[index]?.candidateDocuments.map((document) => document.documentIndex) ?? [])\n ).size\n const chosen = useCases.success\n ? chooseDocumentSets(useCases.match.useCases, attribution.canAnswer, documentsOf)\n : undefined\n const byDocRequest = attribution.answer((chosen ?? []).flatMap(({ documentSet }) => documentSet))\n const docRequestsOf = documents.map((): Array<number> => [])\n for (const [docRequestIndex, documentIndexes] of Array.from(byDocRequest).sort(([a], [b]) => a - b)) {\n for (const documentIndex of documentIndexes) docRequestsOf[documentIndex]?.push(docRequestIndex)\n }\n const answered = {\n useCases: chosen ?? [],\n documents: docRequestsOf.map((docRequestIndexes, documentIndex) => ({ documentIndex, docRequestIndexes })),\n }\n\n if (!useCases.success || !chosen) {\n // Use cases or doc requests that can each be answered, but not together, fail no check of their own.\n const reason = useCases.success\n ? 'Every use case it requires can be answered, but not together: the doc requests with uniqueDocSetRequired among them cannot each have a document that satisfies them'\n : useCases.match.useCasesSource === 'allDocRequests' && docRequests.every(isSuccess)\n ? 'Its doc requests are each satisfied, but not together: those with uniqueDocSetRequired cannot each have a document that satisfies them'\n : undefined\n return {\n success: false,\n ...useCases.match,\n docRequests,\n unrequestedDocuments,\n attribution: answered,\n ...(reason ? { reason } : {}),\n }\n }\n if (useCases.match.useCasesSource !== 'allDocRequests') {\n return {\n success: true,\n useCasesSource: useCases.match.useCasesSource,\n useCases: useCases.match.useCases,\n docRequests,\n unrequestedDocuments,\n attribution: answered,\n }\n }\n // A single use case holding every doc request is only satisfied when all of them are.\n return {\n success: true,\n useCasesSource: 'allDocRequests',\n useCases: useCases.match.useCases,\n docRequests: docRequests.filter(isSuccess),\n unrequestedDocuments,\n attribution: answered,\n }\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 * The doc requests are matched by use case, the same way as {@link matchDeviceRequest} does, and each\n * use case lists the document sets the credentials can answer (`matchingDocumentSets`), of which\n * the holder picks one.\n *\n * The `requestInfo` of a doc request is applied too: a credential of an issuer it does not name\n * fails, and a requested element is answered by one of its alternative sets when the credential\n * has one. The claims list every option, of which the holder can pick another than the first.\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, requestInfo } = 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 issuerResult = matchIssuer(\n requestInfo?.issuerIdentifiers,\n issuerAuthCertificateChain(issuerSigned),\n 'x5chain of the IssuerAuth'\n )\n\n const claimsResult = toClaimsMatchResult(\n matchElements({\n mode: 'holder',\n namespaces,\n issuerSigned,\n keyAuthorizations: mobileSecurityObject.deviceKeyInfo.keyAuthorizations,\n deviceNamespaces,\n alternatives: requestInfo?.alternativeDataElements,\n }).claims\n )\n\n const issuer = issuerResult ? { issuer: issuerResult } : {}\n return docTypeResult.success && claimsResult.success && issuerResult?.success !== false\n ? {\n credentialIndex,\n success: true,\n docType: docTypeResult,\n ...(issuer as { issuer?: IssuerMatchSuccess }),\n claims: claimsResult,\n }\n : { credentialIndex, success: false, docType: docTypeResult, ...issuer, 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 const useCases = matchUseCases(\n resolveUseCases(deviceRequest, options.treatAmbiguousMultipleDocRequestsAsAlternatives),\n docRequests\n )\n if (!useCases.success) return { success: false, ...useCases.match, docRequests }\n if (useCases.match.useCasesSource !== 'allDocRequests') {\n return {\n success: true,\n useCasesSource: useCases.match.useCasesSource,\n useCases: useCases.match.useCases,\n docRequests,\n }\n }\n // A single use case holding every doc request is only satisfied when all of them are.\n return {\n success: true,\n useCasesSource: 'allDocRequests',\n useCases: useCases.match.useCases,\n docRequests: docRequests.filter(isSuccess),\n }\n}\n\ntype ResolvedUseCases = {\n useCasesSource: UseCasesSource\n useCases: Array<{ mandatory: boolean; purposeHints?: Map<string, number>; documentSets: Array<Array<number>> }>\n}\n\n/**\n * The use cases to match the device request by: its own (ISO/IEC TS 23220-4 7.2.1.3.4), and\n * otherwise every doc request as one mandatory use case (7.2.1.3.2), or with\n * `treatAmbiguousMultipleDocRequestsAsAlternatives` each doc request as an optional use case. A\n * single doc request is not ambiguous, so it always is a mandatory use case of its own.\n */\nconst resolveUseCases = (\n deviceRequest: DeviceRequest,\n treatAmbiguousMultipleDocRequestsAsAlternatives = false\n): ResolvedUseCases => {\n const useCases = deviceRequest.deviceRequestInfo?.useCases\n if (useCases) {\n return {\n useCasesSource: 'deviceRequestInfo',\n useCases: useCases.map(({ mandatory, purposeHints, documentSets }) => ({\n mandatory,\n ...(purposeHints ? { purposeHints } : {}),\n documentSets,\n })),\n }\n }\n\n const docRequestIndexes = deviceRequest.docRequests.map((_, docRequestIndex) => docRequestIndex)\n if (treatAmbiguousMultipleDocRequestsAsAlternatives && docRequestIndexes.length > 1) {\n return {\n useCasesSource: 'eachDocRequest',\n useCases: docRequestIndexes.map((docRequestIndex) => ({ mandatory: false, documentSets: [[docRequestIndex]] })),\n }\n }\n\n return { useCasesSource: 'allDocRequests', useCases: [{ mandatory: true, documentSets: [docRequestIndexes] }] }\n}\n\n/**\n * Per use case the document sets whose doc requests are all satisfied, and whether the device\n * request is: every mandatory use case and at least one use case has to be (18013-5 second edition\n * 10.2.5).\n */\nconst matchUseCases = (\n { useCasesSource, useCases }: ResolvedUseCases,\n docRequests: Array<{ success: boolean }>,\n // Whether the doc requests of a set can be answered together, see `createAttribution`.\n canAnswer: (docRequestIndexes: Array<number>) => boolean = () => true\n) => {\n const matches = useCases.map(({ mandatory, purposeHints, documentSets }, useCaseIndex): UseCaseMatch => {\n const satisfied = documentSets.filter(\n (set) => set.every((index) => docRequests[index]?.success === true) && canAnswer(set)\n )\n return {\n useCaseIndex,\n mandatory,\n ...(purposeHints ? { purposeHints } : {}),\n success: satisfied.length > 0,\n documentSets,\n matchingDocumentSets: satisfied,\n }\n })\n\n return {\n match: { useCasesSource, useCases: matches },\n success:\n matches.every((useCase) => !useCase.mandatory || useCase.success) && matches.some((useCase) => useCase.success),\n }\n}\n\n/**\n * One document set per use case, answered together: every mandatory use case, and as many others as\n * can be added in order. The sets of a use case are tried the one `documentsOf` gives most first,\n * then in request order. Undefined when the mandatory use cases cannot be answered together, or\n * without one, when none can be answered. Tries every combination of the sets of the mandatory use\n * cases, which the request sets.\n */\nconst chooseDocumentSets = (\n useCases: Array<UseCaseMatch>,\n canAnswer: (docRequestIndexes: Array<number>) => boolean,\n documentsOf: (documentSet: Array<number>) => number\n): Array<{ useCaseIndex: number; documentSet: Array<number> }> | undefined => {\n const preferences = new Map(\n useCases.map((useCase) => [\n useCase.useCaseIndex,\n useCase.matchingDocumentSets\n .map((documentSet, order) => ({ documentSet, order, documents: documentsOf(documentSet) }))\n .sort((a, b) => b.documents - a.documents || a.order - b.order)\n .map(({ documentSet }) => ({ useCaseIndex: useCase.useCaseIndex, documentSet })),\n ])\n )\n const preferred = (useCase: UseCaseMatch) => preferences.get(useCase.useCaseIndex) ?? []\n\n const mandatory = useCases.filter((useCase) => useCase.mandatory)\n const search = (\n index: number,\n chosen: Array<{ useCaseIndex: number; documentSet: Array<number> }>\n ): typeof chosen | undefined => {\n const useCase = mandatory[index]\n if (!useCase) return chosen\n for (const option of preferred(useCase)) {\n const next = [...chosen, option]\n if (!canAnswer(next.flatMap(({ documentSet }) => documentSet))) continue\n const found = search(index + 1, next)\n if (found) return found\n }\n return undefined\n }\n\n const chosen = search(0, [])\n if (!chosen) return undefined\n for (const useCase of useCases) {\n if (useCase.mandatory) continue\n const option = preferred(useCase).find(({ documentSet }) =>\n canAnswer([...chosen.flatMap((answered) => answered.documentSet), ...documentSet])\n )\n if (option) chosen.push(option)\n }\n chosen.sort((a, b) => a.useCaseIndex - b.useCaseIndex)\n return chosen.length > 0 ? chosen : undefined\n}\n\n/**\n * Whether a document or credential comes from one of `issuerIdentifiers`; undefined when the doc\n * request names no issuer. Matched against the authority key identifiers of `certificateChain`:\n * for a verifier the chain it validated, as the x5chain is in the unprotected header of the\n * IssuerAuth, and for a holder the x5chain of its own credential. Without a chain, it fails.\n *\n * @internal\n */\nexport const matchIssuer = (\n issuerIdentifiers: Array<Uint8Array> | undefined,\n certificateChain: Array<Uint8Array> | undefined,\n chainName: 'validated certificate chain' | 'x5chain of the IssuerAuth'\n): IssuerMatchResult | undefined => {\n if (!issuerIdentifiers) return undefined\n\n const accepted = `the ${issuerIdentifiers.length} issuer identifier(s) the doc request accepts`\n if (!certificateChain) {\n return { success: false, reason: `The document has no ${chainName} to match ${accepted} against` }\n }\n\n const keyIdentifiers = certificateChain.flatMap((certificate) => {\n try {\n return parseCertificate(certificate).authorityKeyIdentifier ?? []\n } catch {\n // A certificate that does not parse has no key identifier to match.\n return []\n }\n })\n\n return issuerIdentifiers.some((identifier) => keyIdentifiers.includes(hexEncode(identifier)))\n ? { success: true }\n : {\n success: false,\n reason: `No certificate in the ${chainName} has one of ${accepted} as its authority key identifier`,\n }\n}\n\n/**\n * The x5chain of the IssuerAuth of a credential, which a holder matches issuers against; undefined\n * when it cannot be read.\n *\n * @internal\n */\nexport const issuerAuthCertificateChain = (issuerSigned: IssuerSigned) => {\n try {\n return issuerSigned.issuerAuth.certificateChain\n } catch {\n return undefined\n }\n}\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 /**\n * The first element of the first option, see `claim.options`.\n */\n element: ElementCandidate\n /**\n * Every option, as `claim.options` lists them, when the element has alternatives.\n */\n options?: NonEmptyArray<ElementOption>\n }\n | { claim: ClaimMatchFailure; element?: undefined; options?: undefined }\n\n/**\n * @internal\n */\nexport type ElementOption = { alternativeElementSetIndex?: number; elements: NonEmptyArray<ElementCandidate> }\n\nconst toDisclosedElement = ({ issuerSignedItem: _, ...element }: ElementCandidate): DisclosedElement => element\n\nconst groupByNamespace = (elements: Array<DisclosedElement>) => {\n const namespaces = new Map<Namespace, Array<DataElementIdentifier>>()\n for (const { namespace, elementIdentifier } of elements) {\n namespaces.set(namespace, [...(namespaces.get(namespace) ?? []), elementIdentifier])\n }\n return namespaces\n}\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 /**\n * The alternative data elements of the `requestInfo` of the doc request (ISO/IEC TS 23220-4\n * 7.2.1.3.2). Each alternative set whose elements all are there (18013-5 second edition 10.2.4),\n * each found the way the requested element would be, is an option to answer the requested element,\n * after the element itself. The first option answers it. For a holder, an alternative set that\n * would make the response disclose more than two age_over_NN elements in a namespace is not an\n * option.\n */\n alternatives?: Array<AlternativeDataElementsSet>\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 inNamespace = (namespace: Namespace, source: DisclosedElementSource) =>\n available.filter((element) => element.namespace === namespace && element.source === source)\n const authorizedDeviceSigned = (namespace: Namespace) =>\n inNamespace(namespace, 'deviceSigned').filter((element) =>\n isDeviceSignedElementAuthorized(keyAuthorizations, element)\n )\n\n /**\n * The element that answers a request for `elementIdentifier` in `namespace`: for a holder\n * issuer-signed, else device-signed when authorized and given for exactly that element; for a\n * verifier from the source its options allow. The same rules as for a requested element.\n */\n const lookup = (namespace: Namespace, elementIdentifier: DataElementIdentifier): ElementCandidate | undefined => {\n if (mode === 'holder') {\n return (\n findElement(elementIdentifier, inNamespace(namespace, 'issuerSigned')) ??\n authorizedDeviceSigned(namespace).find((candidate) => candidate.elementIdentifier === elementIdentifier)\n )\n }\n const namespaceOptions = getOwnProperty(options.elements, namespace)\n const { source = 'issuerSigned' } =\n getOwnProperty(namespaceOptions, elementIdentifier) ?? getOwnProperty(namespaceOptions, '*') ?? {}\n return source === 'deviceSigned'\n ? findElement(elementIdentifier, authorizedDeviceSigned(namespace))\n : (findElement(elementIdentifier, inNamespace(namespace, 'issuerSigned')) ??\n (source === 'any' ? findElement(elementIdentifier, authorizedDeviceSigned(namespace)) : undefined))\n }\n\n /**\n * Every alternative set of the requested element whose elements all are there, in the reader's\n * order; undefined when the doc request has no alternatives for the element.\n */\n const findAlternatives = (namespace: Namespace, elementIdentifier: DataElementIdentifier) => {\n const alternative = options.alternatives?.find(\n ({ requestedElement: [requestedNamespace, requestedIdentifier] }) =>\n requestedNamespace === namespace && requestedIdentifier === elementIdentifier\n )\n if (!alternative) return undefined\n\n return alternative.alternativeElementSets.flatMap((set, alternativeElementSetIndex): Array<ElementOption> => {\n const elements = set.map(([alternativeNamespace, alternativeIdentifier]) =>\n lookup(alternativeNamespace, alternativeIdentifier)\n )\n return elements.every((element) => element !== undefined) && isNonEmptyArray(elements)\n ? [{ alternativeElementSetIndex, elements }]\n : []\n })\n }\n\n /** The options to answer a requested element: itself when it is there, then its alternatives. */\n const optionsFor = (\n namespace: Namespace,\n elementIdentifier: DataElementIdentifier,\n element: ElementCandidate | undefined\n ) => {\n const alternatives = findAlternatives(namespace, elementIdentifier)\n const elementOptions: Array<ElementOption> = [\n ...(element ? [{ elements: [element] as NonEmptyArray<ElementCandidate> }] : []),\n ...(alternatives ?? []),\n ]\n return {\n options: isNonEmptyArray(elementOptions) ? elementOptions : undefined,\n hasAlternatives: alternatives !== undefined,\n }\n }\n\n const claims: Array<ElementMatch> = []\n const usedElements = new Set<DisclosedElement>()\n // Holder claims are only settled once every requested element is looked up, see below.\n const holderClaims: Array<{\n claim: ClaimMatchBase\n element: ElementCandidate | undefined\n elementOptions: Array<ElementOption> | undefined\n hasAlternatives: boolean\n }> = []\n\n /**\n * The claim is answered by the first option. `listOptions` is set when the element has\n * alternatives, so that every option is reported.\n */\n const success = (claim: ClaimMatchBase, elementOptions: NonEmptyArray<ElementOption>, listOptions: boolean) => {\n const [first] = elementOptions\n for (const element of first.elements) usedElements.add(element)\n const [element] = first.elements\n\n claims.push({\n element,\n ...(listOptions ? { options: elementOptions } : {}),\n claim: {\n ...claim,\n success: true,\n disclosedElementIdentifier: element.elementIdentifier,\n elementValue: element.elementValue,\n source: element.source,\n ...(listOptions\n ? {\n options: elementOptions.map(({ alternativeElementSetIndex, elements }) => ({\n ...(alternativeElementSetIndex === undefined ? {} : { alternativeElementSetIndex }),\n elements: elements.map(toDisclosedElement) as NonEmptyArray<DisclosedElement>,\n })) as NonEmptyArray<ClaimMatchOption>,\n }\n : {}),\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 const { options: elementOptions, hasAlternatives } = optionsFor(namespace, elementIdentifier, element)\n holderClaims.push({ claim, element, elementOptions, hasAlternatives })\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 // ISO/IEC TS 23220-4 7.2.1.3.2: an alternative set the request allows answers it too, when every\n // element of it is there (18013-5 second edition 10.2.4).\n const { options: elementOptions, hasAlternatives } = optionsFor(namespace, elementIdentifier, element)\n if (elementOptions) {\n success(claim, elementOptions, hasAlternatives)\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 // 18013-5 7.2.5: at most two age_over_NN elements are disclosed per namespace. The requested\n // elements the credential has are disclosed by default, so an alternative set is only offered when,\n // disclosed with those of the other claims, it keeps every namespace within two.\n for (const [claimIndex, { claim, element, elementOptions, hasAlternatives }] of holderClaims.entries()) {\n const others = holderClaims.flatMap((other, otherIndex) =>\n otherIndex !== claimIndex && other.element ? [other.element] : []\n )\n const options = elementOptions?.filter(\n (option) =>\n option.alternativeElementSetIndex === undefined ||\n findAgeOverLimitViolations(groupByNamespace([...others, ...option.elements])).length === 0\n )\n if (options && isNonEmptyArray(options)) {\n success(claim, options, hasAlternatives)\n continue\n }\n\n const { namespace, elementIdentifier } = claim\n failure(claim, {\n failure: 'notDisclosed',\n reason:\n elementOptions && !element\n ? `Element '${elementIdentifier}' in namespace '${namespace}' is not in the credential, and each of its alternative sets the credential has would disclose more than two age_over_NN elements in a namespace`\n : 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 }\n\n // An element of an alternative set of a requested element is requested too, whether or not it\n // answers it, so disclosing it is not over-disclosure.\n for (const { requestedElement, alternativeElementSets } of options.alternatives ?? []) {\n if (!namespaces.get(requestedElement[0])?.has(requestedElement[1])) continue\n for (const [alternativeNamespace, alternativeIdentifier] of alternativeElementSets.flat()) {\n const element = lookup(alternativeNamespace, alternativeIdentifier)\n if (element) usedElements.add(element)\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\nconst isSuccess = <T extends { success: boolean }>(result: T): result is Extract<T, { success: true }> => result.success\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, and when the\n * device request carries use cases, one check per mandatory use case and one for \"at least one\".\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 // Doc requests that are each satisfied may still not be answered together, see `createAttribution`.\n const failureReasons = (documentSets: Array<Array<number>>) => {\n const docRequestIndexes = documentSets.flat()\n const reasons = match.docRequests\n .filter((docRequest) => !docRequest.success && docRequestIndexes.includes(docRequest.docRequestIndex))\n .map((docRequest) => `Doc request ${docRequest.docRequestIndex}: ${docRequestFailureReason(docRequest)}`)\n const satisfied = new Set(match.docRequests.filter(isSuccess).map((docRequest) => docRequest.docRequestIndex))\n const notTogether = documentSets.filter((set) => set.every((index) => satisfied.has(index)))\n if (notTogether.length > 0) {\n reasons.push(\n `Doc requests ${notTogether.map((set) => set.join(', ')).join('; ')} are each satisfied, but not together: those with uniqueDocSetRequired cannot each have a document that satisfies them`\n )\n }\n return reasons.join('. ')\n }\n\n if (match.useCasesSource === 'deviceRequestInfo') {\n // A mandatory use case is a check of its own; an optional one only counts towards \"at least one\".\n for (const useCase of match.useCases) {\n if (!useCase.mandatory) continue\n const check = `Device response must satisfy mandatory use case ${useCase.useCaseIndex}`\n if (useCase.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: `None of the document sets of use case ${useCase.useCaseIndex} is satisfied. ${failureReasons(useCase.documentSets)}`,\n result,\n })\n }\n }\n\n const check = 'Device response must satisfy at least one use case'\n if (match.useCases.some((useCase) => useCase.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: `No use case is satisfied. ${failureReasons(match.useCases.flatMap((useCase) => useCase.documentSets))}`,\n result,\n })\n }\n } else if (match.useCasesSource === 'eachDocRequest') {\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 if (!match.success && match.reason) {\n onCheck({\n status: 'FAILED',\n check: 'Device response must answer the doc requests it satisfies together',\n category: 'DOCUMENT_FORMAT',\n reason: match.reason,\n result,\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 // A holder answers each use case with exactly one document set (ISO/IEC TS 23220-4 7.2.1.4). A\n // document that may answer a doc request of a use case the response is not taken to answer may be\n // an answer to it with elements left out, and documents of a docType no doc request asks for are\n // reported below.\n const unrequested = new Set(match.unrequestedDocuments.map((document) => document.documentIndex))\n const answeredUseCases = new Set(match.attribution.useCases.map((useCase) => useCase.useCaseIndex))\n const answeredDocRequests = new Set(match.attribution.useCases.flatMap(({ documentSet }) => documentSet))\n const unanswered = new Set(\n match.useCases\n .filter((useCase) => !answeredUseCases.has(useCase.useCaseIndex))\n .flatMap((useCase) => useCase.documentSets.flat())\n )\n // The documents of the docType of a doc request of those use cases, and of an issuer it accepts.\n const mayAnswerUnanswered = new Set(\n match.docRequests\n .filter((docRequest) => unanswered.has(docRequest.docRequestIndex))\n .flatMap((docRequest) => [...docRequest.validDocuments, ...docRequest.failedDocuments])\n .filter((document) => document.docType.success && document.issuer?.success !== false)\n .map((document) => document.documentIndex)\n )\n const unattributed = match.attribution.documents.filter(\n (document) =>\n !unrequested.has(document.documentIndex) &&\n !mayAnswerUnanswered.has(document.documentIndex) &&\n !document.docRequestIndexes.some((docRequestIndex) => answeredDocRequests.has(docRequestIndex))\n )\n if (match.success && unattributed.length > 0) {\n const sets = match.attribution.useCases\n .map(({ useCaseIndex, documentSet }) => `use case ${useCaseIndex} with doc requests ${documentSet.join(', ')}`)\n .join('; ')\n onCheck({\n status: 'WARNING',\n check: 'Device response must only contain documents of one document set per use case',\n category: 'DOCUMENT_FORMAT',\n reason: `${unattributed.length === 1 ? 'Document' : 'Documents'} ${unattributed.map((document) => document.documentIndex).join(', ')} ${unattributed.length === 1 ? 'answers' : 'answer'} no doc request of the document sets the use cases are answered with (${sets})`,\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 if (!docRequest.success && docRequest.reason) return docRequest.reason\n\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 const reasons = [\n ...(document.issuer && !document.issuer.success ? [document.issuer.reason] : []),\n ...failedClaims.map((claim) => claim.reason),\n ]\n return `Document ${document.documentIndex}: ${reasons.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 zDeviceSigned = typedMap([\n ['nameSpaces', z.instanceof(DeviceNamespaces)],\n ['deviceAuth', z.instanceof(DeviceAuth)],\n] as const)\n\nexport type DeviceSignedDecodedStructure = z.output<typeof zDeviceSigned>\nexport type DeviceSignedEncodedStructure = z.input<typeof zDeviceSigned>\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(zDeviceSigned.in, zDeviceSigned.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 zErrorItems = 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 zErrorItems\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, zErrorItems } from './error-items'\nimport type { Namespace } from './namespace'\n\nconst zErrorsEncoded = z.map(z.string(), zErrorItems)\nconst zErrorsDecoded = z.map(z.string(), z.instanceof(ErrorItems))\n\nexport type ErrorsEncodedStructure = z.infer<typeof zErrorsEncoded>\nexport type ErrorsDecodedStructure = z.infer<typeof zErrorsDecoded>\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(zErrorsEncoded, zErrorsDecoded, {\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 zDocument = 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 zDocument>\nexport type DocumentEncodedStructure = z.input<typeof zDocument>\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(zDocument.in, zDocument.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 zDocumentError = z.map(z.string(), z.number())\n\nexport type DocumentErrorStructure = z.infer<typeof zDocumentError>\n\nexport type DocumentErrorOptions = {\n documentError: DocumentErrorStructure\n}\n\nexport class DocumentError extends CborStructure<DocumentErrorStructure> {\n public static override get encodingSchema() {\n return zDocumentError\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 type ElementMatch,\n issuerAuthCertificateChain,\n matchDeviceRequest,\n matchElements,\n matchIssuer,\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 UnsatisfiedDeviceRequestError,\n} from '../errors'\nimport type { AlternativeDataElementsSet } from './alternative-data-elements-set'\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 { IntentToRetain } from './intent-to-retain'\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 { StatusVerificationOptions } from './mso-revocation-list'\nimport type { Namespace } from './namespace'\nimport type { SessionTranscript } from './session-transcript'\n\n/**\n * Whether a requested element is answered by one of its alternative sets, which a holder only\n * discloses when it chooses one: the credential does not have the element itself.\n */\nconst isAnsweredByAlternative = (match: ElementMatch) => match.options?.[0].alternativeElementSetIndex !== undefined\n\nconst zDeviceResponseEncoded = 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 zDeviceResponseDecoded = 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 zDeviceResponseEncoded>\nexport type DeviceResponseDecodedStructure = z.output<typeof zDeviceResponseDecoded>\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, or of every\n * doc request it answers, which then all have its docType. The document discloses the elements\n * all of them request, and counts as their document for `uniqueDocSetRequired` and the use cases.\n */\n docRequestIndex: number | Array<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 * For a requested element that has alternatives in the `requestInfo` of the doc request (ISO/IEC\n * TS 23220-4 7.2.1.3.2, 18013-5 second edition 10.2.4), the index into its `alternativeElementSets`\n * of the set to disclose in its place, per namespace and element. For a document that answers\n * several doc requests, the ones that request the element must have the same alternatives for it. Every element of the set is\n * disclosed, possibly in other namespaces. The `options` of the claims of `Holder.matchDeviceRequest`\n * list the sets the credential can disclose.\n *\n * An alternative set is only disclosed when it is chosen here, so that nothing is disclosed that\n * the holder was not shown. By default the element itself is disclosed, and a requested element the\n * credential does not have throws a `MissingRequestedElementError`, even when an alternative set\n * could answer it.\n *\n * Throws an `InvalidElementSelectionError` for an element the doc request does not request, a set\n * it does not have, an element that `elements` leaves out, a set that discloses an element that\n * `elements` leaves out, or an element that the doc requests of the document have different\n * alternatives for; and a `MissingRequestedElementError` for a set the credential does not have\n * every element of.\n */\n alternatives?: Record<Namespace, Record<DataElementIdentifier, number>>\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, and of the alternative sets chosen in `alternatives`, are\n * disclosed and authenticated, so a value that is not requested or that `elements` leaves out is\n * 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(zDeviceResponseEncoded.in, zDeviceResponseDecoded.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 trustedCertificates: Array<{ issuance: Uint8Array[]; status?: Uint8Array[] }>\n now?: Date\n onCheck?: VerificationCallback\n skewSeconds?: number\n status?: StatusVerificationOptions\n },\n ctx: Pick<MdocContext, 'cose' | 'x509' | 'crypto' | 'fetch' | 'fetchLimits'>\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 status: options.status,\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 // The x5chain is not signed, so issuers are matched against the validated chains.\n issuerCertificateChains: documentResults.map(({ trustedIssuanceChain }) => trustedIssuanceChain),\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 the doc requests it answers, authenticated with either a\n * device signature or a device MAC.\n */\n private static async createDocument(\n options: {\n docRequests: Array<{ docRequestIndex: number; docRequest: DocRequest }>\n sessionTranscript: SessionTranscript | Uint8Array\n issuerSigned: IssuerSigned\n elements?: Record<Namespace, Array<DataElementIdentifier>>\n alternatives?: Record<Namespace, Record<DataElementIdentifier, number>>\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 // 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 const docType = mobileSecurityObject.docType\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 for (const { docRequestIndex, docRequest } of options.docRequests) {\n if (docRequest.itemsRequest.docType !== docType) {\n throw new DocTypeMismatchError(\n `Credential has docType '${docType}', but doc request ${docRequestIndex} requests docType '${docRequest.itemsRequest.docType}'`\n )\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 ...DeviceResponse.mergeDocRequests(options.docRequests),\n docRequestIndexes: options.docRequests.map(({ docRequestIndex }) => docRequestIndex),\n issuerSigned: options.issuerSigned,\n keyAuthorizations,\n deviceNamespaces: options.deviceNamespaces,\n elements: options.elements,\n alternatives: options.alternatives,\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, or the alternative sets chosen for them, are disclosed,\n * from either source: a device-signed element that is not requested, or that `elements` leaves\n * out, is not disclosed.\n */\n private static selectElements(options: {\n namespaces: Map<Namespace, Map<DataElementIdentifier, IntentToRetain>>\n alternativeDataElements: Array<AlternativeDataElementsSet> | undefined\n /**\n * The requested elements that the doc requests have different alternatives for, which cannot be\n * chosen, with the doc requests that request them.\n */\n conflictingAlternatives: Array<{\n namespace: Namespace\n elementIdentifier: DataElementIdentifier\n docRequestIndexes: Array<number>\n }>\n /**\n * The doc requests the document answers, for the error messages.\n */\n docRequestIndexes: Array<number>\n issuerSigned: IssuerSigned\n keyAuthorizations: KeyAuthorizations | undefined\n deviceNamespaces?: DeviceNamespaces\n elements?: Record<Namespace, Array<DataElementIdentifier>>\n alternatives?: Record<Namespace, Record<DataElementIdentifier, number>>\n }) {\n const { claims } = matchElements({\n mode: 'holder',\n namespaces: options.namespaces,\n issuerSigned: options.issuerSigned,\n keyAuthorizations: options.keyAuthorizations,\n deviceNamespaces: options.deviceNamespaces,\n alternatives: options.alternativeDataElements,\n })\n\n const several = options.docRequestIndexes.length > 1\n const docRequests = several ? `doc requests ${options.docRequestIndexes.join(', ')}` : 'the doc request'\n const doNotRequest = `${docRequests} ${several ? 'do' : 'does'} not request`\n\n if (options.elements) {\n for (const [namespace, elementIdentifiers] of Object.entries(options.elements)) {\n for (const elementIdentifier of elementIdentifiers) {\n if (!options.namespaces.get(namespace)?.has(elementIdentifier)) {\n throw new InvalidElementSelectionError(\n `Element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but ${doNotRequest} 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 const requestedAlternatives = options.alternativeDataElements\n for (const [namespace, chosen] of Object.entries(options.alternatives ?? {})) {\n for (const [elementIdentifier, alternativeElementSetIndex] of Object.entries(chosen)) {\n if (!options.namespaces.get(namespace)?.has(elementIdentifier)) {\n throw new InvalidElementSelectionError(\n `Alternative set ${alternativeElementSetIndex} of element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but ${doNotRequest} the element`\n )\n }\n const sets = requestedAlternatives?.find(\n ({ requestedElement: [requestedNamespace, requestedIdentifier] }) =>\n requestedNamespace === namespace && requestedIdentifier === elementIdentifier\n )?.alternativeElementSets\n const conflict = options.conflictingAlternatives.find(\n (element) => element.namespace === namespace && element.elementIdentifier === elementIdentifier\n )\n if (conflict) {\n throw new InvalidElementSelectionError(\n `Alternative set ${alternativeElementSetIndex} of element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but doc requests ${conflict.docRequestIndexes.join(', ')} have different alternatives for it. Answer them with separate documents`\n )\n }\n if (!sets?.[alternativeElementSetIndex]) {\n throw new InvalidElementSelectionError(\n `Alternative set ${alternativeElementSetIndex} of element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but ${docRequests} ${several ? 'have' : 'has'} no such alternative set`\n )\n }\n if (options.elements && !getOwnProperty(options.elements, namespace)?.includes(elementIdentifier)) {\n throw new InvalidElementSelectionError(\n `Alternative set ${alternativeElementSetIndex} of element '${elementIdentifier}' in namespace '${namespace}' is selected for disclosure, but the element itself is not selected`\n )\n }\n }\n }\n\n // The element of each requested element left out of the selection, with that claim. One that the\n // credential does not have, and that an alternative set answers, has none to leave out.\n const declinedElements = new Map(\n claims.flatMap((match) =>\n match.element && !isAnsweredByAlternative(match) && !isSelected(match.claim)\n ? [[match.element, match.claim] as const]\n : []\n )\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) {\n const conflict = options.conflictingAlternatives.find(\n (element) => element.namespace === claim.namespace && element.elementIdentifier === claim.elementIdentifier\n )\n throw new MissingRequestedElementError(\n conflict\n ? `Element '${claim.elementIdentifier}' in namespace '${claim.namespace}' is not in the credential, and doc requests ${conflict.docRequestIndexes.join(', ')} have different alternatives for it. Answer them with separate documents`\n : match.claim.reason\n )\n }\n const { element } = match\n\n const alternativeElementSetIndex = getOwnProperty(\n getOwnProperty(options.alternatives, claim.namespace),\n claim.elementIdentifier\n )\n const chosen =\n alternativeElementSetIndex === undefined\n ? undefined\n : match.options?.find((option) => option.alternativeElementSetIndex === alternativeElementSetIndex)\n if (alternativeElementSetIndex !== undefined && !chosen) {\n throw new MissingRequestedElementError(\n `Alternative set ${alternativeElementSetIndex} of element '${claim.elementIdentifier}' in namespace '${claim.namespace}' is selected for disclosure, but the credential cannot disclose every element of it`\n )\n }\n\n // An alternative set is only disclosed when the holder chooses it, so that nothing is disclosed\n // that the holder was not shown: the requested element may be answered by elements in other\n // namespaces, which the claim does not describe.\n if (isAnsweredByAlternative(match) && !chosen) {\n throw new MissingRequestedElementError(\n `Element '${claim.elementIdentifier}' in namespace '${claim.namespace}' is not in the credential. Choose one of its alternative sets ${match.options?.map((option) => option.alternativeElementSetIndex).join(', ')} with \\`alternatives\\` to disclose in its place`\n )\n }\n\n // An alternative set (18013-5 second edition 10.2.4) is disclosed whole, each element in its\n // own namespace, which need not be the requested element's.\n const disclosedElements = chosen?.elements ?? [element]\n\n // An element left out must not be disclosed for another requested element, neither as an age\n // attestation that answers both (18013-5 7.2.5) nor in an alternative set, or leaving it out\n // would have no effect.\n for (const disclosed of disclosedElements) {\n const declined = declinedElements.get(disclosed)\n if (!declined) continue\n\n const selected = `Element '${claim.elementIdentifier}' in namespace '${claim.namespace}' is selected for disclosure`\n if (!chosen) {\n throw new InvalidElementSelectionError(\n `${selected}, but it is answered with '${disclosed.elementIdentifier}', which also answers '${declined.elementIdentifier}' that is not selected. Select both or neither`\n )\n }\n const answer =\n disclosed.namespace === declined.namespace && disclosed.elementIdentifier === declined.elementIdentifier\n ? `'${disclosed.elementIdentifier}' in namespace '${disclosed.namespace}'`\n : `'${disclosed.elementIdentifier}' in namespace '${disclosed.namespace}', which answers '${declined.elementIdentifier}' in namespace '${declined.namespace}'`\n throw new InvalidElementSelectionError(\n `${selected}, but it is answered with alternative set ${chosen.alternativeElementSetIndex}, which discloses ${answer} that is not selected. Select both, or choose another alternative set`\n )\n }\n\n for (const disclosed of disclosedElements) {\n if (!disclosed.issuerSignedItem) {\n const items = deviceNamespaces.get(disclosed.namespace) ?? new Map()\n items.set(disclosed.elementIdentifier, disclosed.elementValue)\n deviceNamespaces.set(disclosed.namespace, items)\n continue\n }\n\n const items = issuerNamespaces.get(disclosed.namespace) ?? []\n // An age attestation can answer more than one `age_over_NN` request, but is disclosed once.\n if (!items.includes(disclosed.issuerSignedItem)) items.push(disclosed.issuerSignedItem)\n issuerNamespaces.set(disclosed.namespace, items)\n }\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 `${several ? `Doc requests ${options.docRequestIndexes.join(', ')}` : '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${options.alternatives && Object.keys(options.alternatives).length > 0 ? ', or choose other alternative sets' : ''}`\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 /**\n * The doc requests a document answers, from its `docRequestIndex`.\n */\n private static findDocRequests(\n deviceRequest: DeviceRequest,\n document: Pick<DeviceResponseDocumentOptions, 'docRequestIndex'>\n ) {\n const docRequestIndexes = Array.from(\n new Set(typeof document.docRequestIndex === 'number' ? [document.docRequestIndex] : document.docRequestIndex)\n )\n if (docRequestIndexes.length === 0) throw new Error('A document has to answer at least one doc request')\n\n return docRequestIndexes.map((docRequestIndex) => ({\n docRequestIndex,\n docRequest: DeviceResponse.findDocRequest(deviceRequest, docRequestIndex),\n }))\n }\n\n /**\n * What the doc requests of a document request together: every element any of them requests, and\n * its alternatives. An element that more than one of them requests with different alternatives,\n * or without alternatives in one of them, is answered by itself only: an alternative set of one\n * doc request would not answer the other.\n */\n private static mergeDocRequests(docRequests: Array<{ docRequestIndex: number; docRequest: DocRequest }>) {\n const namespaces = new Map<Namespace, Map<DataElementIdentifier, IntentToRetain>>()\n for (const { docRequest } of docRequests) {\n for (const [namespace, elements] of docRequest.itemsRequest.namespaces) {\n const merged = namespaces.get(namespace) ?? new Map<DataElementIdentifier, IntentToRetain>()\n for (const [elementIdentifier, intentToRetain] of elements) {\n merged.set(elementIdentifier, (merged.get(elementIdentifier) ?? false) || intentToRetain)\n }\n namespaces.set(namespace, merged)\n }\n }\n\n const alternativeDataElements: Array<AlternativeDataElementsSet> = []\n const conflictingAlternatives: Array<{\n namespace: Namespace\n elementIdentifier: DataElementIdentifier\n docRequestIndexes: Array<number>\n }> = []\n for (const [namespace, elements] of namespaces) {\n for (const elementIdentifier of elements.keys()) {\n const requesting = docRequests.filter(({ docRequest }) =>\n docRequest.itemsRequest.namespaces.get(namespace)?.has(elementIdentifier)\n )\n const alternatives = requesting.map(({ docRequest }) =>\n docRequest.itemsRequest.requestInfo?.alternativeDataElements?.find(\n ({ requestedElement: [requestedNamespace, requestedIdentifier] }) =>\n requestedNamespace === namespace && requestedIdentifier === elementIdentifier\n )\n )\n const [first] = alternatives\n if (!first) {\n if (alternatives.some((alternative) => alternative)) {\n conflictingAlternatives.push({\n namespace,\n elementIdentifier,\n docRequestIndexes: requesting.map(({ docRequestIndex }) => docRequestIndex),\n })\n }\n continue\n }\n const sameSets = (alternative: AlternativeDataElementsSet | undefined) =>\n JSON.stringify(alternative?.alternativeElementSets) === JSON.stringify(first.alternativeElementSets)\n if (alternatives.every(sameSets)) {\n alternativeDataElements.push(first)\n } else {\n conflictingAlternatives.push({\n namespace,\n elementIdentifier,\n docRequestIndexes: requesting.map(({ docRequestIndex }) => docRequestIndex),\n })\n }\n }\n }\n\n return {\n namespaces,\n alternativeDataElements: alternativeDataElements.length > 0 ? alternativeDataElements : undefined,\n conflictingAlternatives,\n }\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 * Throw an `UnsatisfiedDeviceRequestError` when the documents do not answer the device request the\n * way its request information asks (ISO/IEC TS 23220-4 7.2.1.3): a document of an issuer its doc\n * request does not name, more than one document for a doc request that requires a unique document\n * set, or, when the device request carries use cases, a mandatory use case, or every use case, left\n * without a document set whose doc requests all have a document.\n *\n * Only which doc requests get a document is checked, not which elements are disclosed, so the\n * holder can still leave elements out. A doc request has a document when a document names it in\n * its `docRequestIndex`, as one document can answer several doc requests. A response without any\n * document is not checked, as that is how a holder declines a request it\n * cannot or does not want to satisfy (18013-5 second edition 10.2.1).\n *\n * A device request without use cases does not say whether it asks for all its doc requests or for\n * any one of them: ISO/IEC TS 23220-4 7.2.1.3.2 reads it as all of them, but the iOS DC API presents\n * it as alternatives, so readers use it that way (see `treatAmbiguousMultipleDocRequestsAsAlternatives`).\n * Which doc requests get a document is then not checked.\n */\n private static checkRequestInfo(deviceRequest: DeviceRequest, documents: Array<DeviceResponseDocumentOptions>) {\n const documentsPerDocRequest = new Map<number, number>()\n\n for (const [documentIndex, document] of documents.entries()) {\n for (const { docRequestIndex, docRequest } of DeviceResponse.findDocRequests(deviceRequest, document)) {\n const { requestInfo } = docRequest.itemsRequest\n documentsPerDocRequest.set(docRequestIndex, (documentsPerDocRequest.get(docRequestIndex) ?? 0) + 1)\n\n const issuer = matchIssuer(\n requestInfo?.issuerIdentifiers,\n issuerAuthCertificateChain(document.issuerSigned),\n 'x5chain of the IssuerAuth'\n )\n if (issuer && !issuer.success) {\n throw new UnsatisfiedDeviceRequestError(\n `Document ${documentIndex} answers doc request ${docRequestIndex}, but comes from an issuer it does not accept: ${issuer.reason}`\n )\n }\n\n if (requestInfo?.uniqueDocSetRequired && documentsPerDocRequest.get(docRequestIndex) === 2) {\n throw new UnsatisfiedDeviceRequestError(\n `More than one document answers doc request ${docRequestIndex}, but it requires a unique document set`\n )\n }\n }\n }\n\n const useCases = deviceRequest.deviceRequestInfo?.useCases\n if (!useCases || documents.length === 0) return\n\n const hasDocument = (docRequestIndex: number) => documentsPerDocRequest.has(docRequestIndex)\n const isSatisfied = (documentSets: Array<Array<number>>) => documentSets.some((set) => set.every(hasDocument))\n const answered = `they answer doc requests ${Array.from(documentsPerDocRequest.keys())\n .sort((a, b) => a - b)\n .join(', ')}`\n\n for (const [useCaseIndex, useCase] of useCases.entries()) {\n if (useCase.mandatory && !isSatisfied(useCase.documentSets)) {\n throw new UnsatisfiedDeviceRequestError(\n `Use case ${useCaseIndex} is mandatory, but the documents do not answer every doc request of any of its document sets (${answered})`\n )\n }\n }\n if (!useCases.some((useCase) => isSatisfied(useCase.documentSets))) {\n throw new UnsatisfiedDeviceRequestError(\n `None of the use cases has a document set whose doc requests the documents all answer (${answered})`\n )\n }\n }\n\n /**\n * Throw an `UnsatisfiedDeviceRequestError` when the response is larger than the smallest\n * `maximumResponseSize` of the doc requests, the size in bytes of the unencrypted device response\n * the reader can accept (ISO/IEC TS 23220-4 7.2.1.3.2).\n */\n private static checkResponseSize(deviceRequest: DeviceRequest, deviceResponse: DeviceResponse) {\n const limits = deviceRequest.docRequests.flatMap((docRequest, docRequestIndex) => {\n const maximumResponseSize = docRequest.itemsRequest.requestInfo?.maximumResponseSize\n return maximumResponseSize === undefined ? [] : [{ docRequestIndex, maximumResponseSize }]\n })\n if (limits.length === 0) return\n\n const limit = limits.reduce((smallest, current) =>\n current.maximumResponseSize < smallest.maximumResponseSize ? current : smallest\n )\n const size = deviceResponse.encode().length\n if (size > limit.maximumResponseSize) {\n throw new UnsatisfiedDeviceRequestError(\n `The device response is ${size} bytes, but doc request ${limit.docRequestIndex} accepts at most ${limit.maximumResponseSize}. Leave out elements or documents`\n )\n }\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 requests it answers through `docRequestIndex`. Elements and doc requests may be left out,\n * as long as the response still answers the request the way its request information asks: see\n * `Holder.createDeviceResponseForDeviceRequest` for what is refused.\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 DeviceResponse.checkRequestInfo(options.deviceRequest, options.documents)\n\n const documents = await Promise.all(\n options.documents.map((document) =>\n DeviceResponse.createDocument(\n {\n docRequests: DeviceResponse.findDocRequests(options.deviceRequest, document),\n sessionTranscript: options.sessionTranscript,\n issuerSigned: document.issuerSigned,\n elements: document.elements,\n alternatives: document.alternatives,\n deviceNamespaces: document.deviceNamespaces,\n signature: document.signature,\n mac: document.mac,\n },\n ctx\n )\n )\n )\n\n const deviceResponse = DeviceResponse.fromDocuments(documents)\n DeviceResponse.checkResponseSize(options.deviceRequest, deviceResponse)\n return deviceResponse\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 zEncryptedResponseData = typedMap([\n ['enc', zUint8Array],\n ['cipherText', zUint8Array],\n] as const)\n\nexport type EncryptedResponseDataDecodedStructure = z.output<typeof zEncryptedResponseData>\nexport type EncryptedResponseDataEncodedStructure = z.input<typeof zEncryptedResponseData>\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 zEncryptedResponseData\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 zEncryptedResponseEncoded = z.tuple([z.literal('dcapi'), z.map(z.unknown(), z.unknown())])\nconst zEncryptedResponseDecoded = z.instanceof(EncryptedResponseData)\n\nexport type EncryptedResponseEncodedStructure = z.infer<typeof zEncryptedResponseEncoded>\nexport type EncryptedResponseDecodedStructure = z.infer<typeof zEncryptedResponseDecoded>\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(zEncryptedResponseEncoded, zEncryptedResponseDecoded, {\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 zEncryptionParameters = typedMap([\n ['nonce', zUint8Array],\n ['recipientPublicKey', z.instanceof(CoseKey)],\n] as const)\n\nexport type EncryptionParametersDecodedStructure = z.output<typeof zEncryptionParameters>\nexport type EncryptionParametersEncodedStructure = z.input<typeof zEncryptionParameters>\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(zEncryptionParameters.in, zEncryptionParameters.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 zEncryptionInfoEncoded = z.tuple([z.literal('dcapi'), z.map(z.unknown(), z.unknown())])\nconst zEncryptionInfoDecoded = z.instanceof(EncryptionParameters)\n\nexport type EncryptionInfoEncodedStructure = z.infer<typeof zEncryptionInfoEncoded>\nexport type EncryptionInfoDecodedStructure = z.infer<typeof zEncryptionInfoDecoded>\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(zEncryptionInfoEncoded, zEncryptionInfoDecoded, {\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","import { HashAlgorithm } from '@owf/cose'\nimport type { MdocContext } from '../context'\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\n/**\n * The value of a protected `x5t` COSE header (RFC 9360) for the leaf of a certificate chain, with\n * SHA-256 as 18013-5 (second edition) 12.3.4 and 12.5.4 require.\n */\nexport const x5tHeaderValue = async (certificateChain: Array<Uint8Array>, ctx: Pick<MdocContext, 'crypto'>) => [\n HashAlgorithm.SHA256,\n await ctx.crypto.digest({ digestAlgorithm: 'SHA-256', bytes: certificateChain[0] }),\n]\n","import {\n type CoseKey,\n type DigestAlgorithm,\n ProtectedHeaders,\n RegisteredCwtHeaderClaimKey,\n type SignatureAlgorithm,\n UnprotectedHeaders,\n} from '@owf/cose'\nimport { stringToBytes } from '@owf/identity-common'\nimport type { MdocContext } from '../../context'\nimport { randomUnsignedInteger } from '../../utils/randomUnsignedInteger'\nimport { x5chainHeaderValue, x5tHeaderValue } 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 /**\n * Add a SHA-256 `x5t` of the leaf certificate to the protected header, as the second edition of\n * ISO/IEC 18013-5 recommends. Off by default, as the first edition has nothing but `alg` there.\n */\n includeX5t?: boolean\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<number, unknown>([[RegisteredCwtHeaderClaimKey.Algorithm, options.algorithm]]),\n })\n if (options.includeX5t) {\n protectedHeaders.headers.set(\n RegisteredCwtHeaderClaimKey.X5T,\n await x5tHeaderValue(options.certificates, this.ctx)\n )\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 StatusVerificationOptions,\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 trustedCertificates?: Array<{ issuance: Uint8Array[]; status?: Uint8Array[] }>\n skewSeconds?: number\n status?: StatusVerificationOptions\n },\n ctx: Pick<MdocContext, 'cose' | 'x509' | 'crypto' | 'fetch' | 'fetchLimits'>\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' | 'crypto'>\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`. A requested\n * element the credential only answers with an alternative set is the exception: the holder has to\n * choose the set with `alternatives`.\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 /**\n * Create a device response for a device request, with one document per entry of `documents`.\n *\n * Throws an `UnsatisfiedDeviceRequestError` when the documents do not answer the device request\n * the way its request information asks (ISO/IEC TS 23220-4 7.2.1.3):\n *\n * - a document of an issuer its doc request does not name\n * - more than one document for a doc request with `uniqueDocSetRequired`\n * - when the device request carries use cases, a mandatory use case, or every use case, left\n * without a document for each doc request of one of its document sets. A document counts for\n * the doc requests its `docRequestIndex` names, so one document can answer several doc\n * requests of its docType. Without use cases this is not checked, as the iOS DC API presents\n * several doc requests as alternatives, see `treatAmbiguousMultipleDocRequestsAsAlternatives`\n * - a response larger than the smallest `maximumResponseSize` of the doc requests\n *\n * Elements can still be left out, and an empty `documents` declines the request.\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 type DeviceRequestInfo,\n type DeviceRequestInfoOptions,\n DeviceResponse,\n type DeviceResponseDocumentOptions,\n type DeviceResponseVerificationResult,\n DocRequest,\n type DocRequestInfo,\n type DocRequestInfoOptions,\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 StatusVerificationOptions,\n type VerificationCallback,\n} from './mdoc'\nimport { verifyAgeOverRequestLimit } from './utils/ageOver'\nimport type { DeviceRequestMatchOptions } from './utils/matchDeviceRequest'\nimport { verifyVersion } from './utils/version'\nimport { x5chainHeaderValue, x5tHeaderValue } 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 zBase64Url = 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 zIsoMdocDcApiRequest = z.object({\n deviceRequest: zBase64Url,\n encryptionInfo: zBase64Url,\n})\nexport type IsoMdocDcApiRequest = z.infer<typeof zIsoMdocDcApiRequest>\n\n/**\n * Response payload returned over the DC API (C.3), base64url-no-pad encoded CBOR.\n */\nexport const zIsoMdocDcApiResponse = z.object({\n response: zBase64Url,\n})\nexport type IsoMdocDcApiResponse = z.infer<typeof zIsoMdocDcApiResponse>\n\n/**\n * The response as it may be handed to {@link IsoMdocDcApi.decryptResponse}, normalized to the\n * base64url `response` string.\n */\nconst zIsoMdocDcApiResponseInput = z.union([zBase64Url, zIsoMdocDcApiResponse.transform(({ response }) => response)])\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 * Alternative data elements, issuer identifiers and the other request information of the doc\n * request (ISO/IEC TS 23220-4 7.2.1.3.2). Covered by its reader auth.\n */\n requestInfo?: DocRequestInfo | DocRequestInfoOptions\n }>\n /**\n * The use cases of the device request (ISO/IEC TS 23220-4 7.2.1.3.4): which doc requests answer\n * what. `version` then defaults to `'1.1'`. Reader auth covers each doc request, not this.\n */\n deviceRequestInfo?: DeviceRequestInfo | DeviceRequestInfoOptions\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 * Add a SHA-256 `x5t` of the leaf certificate to the protected header, as the second edition of\n * ISO/IEC 18013-5 recommends. Off by default, as the first edition has nothing but `alg` there.\n */\n includeX5t?: boolean\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, requestInfo }) => {\n const itemsRequest = ItemsRequest.create({ docType, namespaces, requestInfo })\n\n if (!options.readerAuth || !sessionTranscript) {\n return DocRequest.create({ itemsRequest })\n }\n\n const { signingKey, certificateChain, includeX5t } = 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<number, unknown>([\n [RegisteredCwtHeaderClaimKey.Algorithm, signingKey.algorithm],\n ...(includeX5t\n ? [[RegisteredCwtHeaderClaimKey.X5T, await x5tHeaderValue(certificateChain, ctx)] as [number, unknown]]\n : []),\n ]),\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({\n version: options.version,\n docRequests,\n deviceRequestInfo: options.deviceRequestInfo,\n })\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(zIsoMdocDcApiRequest, 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 requests 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<\n DeviceResponseDocumentOptions,\n 'issuerSigned' | 'docRequestIndex' | 'elements' | 'alternatives' | 'deviceNamespaces'\n > & {\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 alternatives: document.alternatives,\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 zIsoMdocDcApiResponseInput,\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 onCheck?: VerificationCallback\n now?: Date\n skewSeconds?: number\n status?: StatusVerificationOptions\n },\n ctx: Pick<MdocContext, 'crypto' | 'cose' | 'x509' | 'fetch' | 'fetchLimits'>\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 onCheck: options.onCheck,\n now: options.now,\n skewSeconds: options.skewSeconds,\n status: options.status,\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 /**\n * Add a SHA-256 `x5t` of the leaf certificate to the protected header, as the second edition of\n * ISO/IEC 18013-5 recommends. Off by default, as the first edition has nothing but `alg` there.\n */\n includeX5t?: boolean\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 type StatusVerificationOptions,\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 trustedCertificates: Array<{ issuance: Uint8Array[]; status?: Uint8Array[] }>\n now?: Date\n onCheck?: VerificationCallback\n skewSeconds?: number\n status?: StatusVerificationOptions\n },\n ctx: Pick<MdocContext, 'cose' | 'x509' | 'crypto' | 'fetch' | 'fetchLimits'>\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 /**\n * See `issuerCertificateChains` of {@link matchDeviceRequest}: without them, no document\n * satisfies a doc request that names issuers, as the x5chain is not trusted.\n */\n issuerCertificateChains?: Array<Array<Uint8Array> | undefined>\n }): DeviceRequestMatchResult {\n return matchDeviceRequest({\n matchOptions: options.matchOptions,\n issuerCertificateChains: options.issuerCertificateChains,\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":";;;;;;;;;;;;;AAYA,IAAY,cAAL,yBAAA,aAAA;;CAEL,YAAA,4CAAA;;CAGA,YAAA,4CAAA;;CAGA,YAAA,8CAAA;;AACF,EAAA,CAAA,CAAA;;ACjBA,IAAa,WAAb,cAA8B,cAAc;CAC1C,YAAY,UAAkB,WAAW,MAAM;EAC7C,MAAM,OAAO;CACf;AACF;AAEA,IAAa,gBAAb,cAAmC,SAAS,CAAC;AAC7C,IAAa,0CAAb,cAA6D,SAAS,CAAC;;;;;;AAOvE,IAAa,8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