@vanaheimr/cose 0.9.0

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.
Files changed (57) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/LICENSE.md +201 -0
  3. package/NOTICE +31 -0
  4. package/README.md +537 -0
  5. package/dist/aes.d.ts +45 -0
  6. package/dist/aes.d.ts.map +1 -0
  7. package/dist/algorithm.d.ts +137 -0
  8. package/dist/algorithm.d.ts.map +1 -0
  9. package/dist/asn1.d.ts +114 -0
  10. package/dist/asn1.d.ts.map +1 -0
  11. package/dist/cbor.d.ts +65 -0
  12. package/dist/cbor.d.ts.map +1 -0
  13. package/dist/curve.d.ts +65 -0
  14. package/dist/curve.d.ts.map +1 -0
  15. package/dist/ecdsa.d.ts +56 -0
  16. package/dist/ecdsa.d.ts.map +1 -0
  17. package/dist/eddsa.d.ts +14 -0
  18. package/dist/eddsa.d.ts.map +1 -0
  19. package/dist/encrypt.d.ts +140 -0
  20. package/dist/encrypt.d.ts.map +1 -0
  21. package/dist/errors.d.ts +64 -0
  22. package/dist/errors.d.ts.map +1 -0
  23. package/dist/headers.d.ts +77 -0
  24. package/dist/headers.d.ts.map +1 -0
  25. package/dist/hmac.d.ts +32 -0
  26. package/dist/hmac.d.ts.map +1 -0
  27. package/dist/index.d.ts +87 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +4159 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/key.d.ts +201 -0
  32. package/dist/key.d.ts.map +1 -0
  33. package/dist/labels.d.ts +51 -0
  34. package/dist/labels.d.ts.map +1 -0
  35. package/dist/mac.d.ts +93 -0
  36. package/dist/mac.d.ts.map +1 -0
  37. package/dist/mac0.d.ts +132 -0
  38. package/dist/mac0.d.ts.map +1 -0
  39. package/dist/mldsa.d.ts +29 -0
  40. package/dist/mldsa.d.ts.map +1 -0
  41. package/dist/payload.d.ts +25 -0
  42. package/dist/payload.d.ts.map +1 -0
  43. package/dist/recipient.d.ts +65 -0
  44. package/dist/recipient.d.ts.map +1 -0
  45. package/dist/resolve.d.ts +29 -0
  46. package/dist/resolve.d.ts.map +1 -0
  47. package/dist/sign.d.ts +82 -0
  48. package/dist/sign.d.ts.map +1 -0
  49. package/dist/sign1.d.ts +273 -0
  50. package/dist/sign1.d.ts.map +1 -0
  51. package/dist/signature.d.ts +43 -0
  52. package/dist/signature.d.ts.map +1 -0
  53. package/dist/x509.d.ts +144 -0
  54. package/dist/x509.d.ts.map +1 -0
  55. package/dist/x5chain.d.ts +98 -0
  56. package/dist/x5chain.d.ts.map +1 -0
  57. package/package.json +97 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/cbor.ts","../src/payload.ts","../src/labels.ts","../src/curve.ts","../src/ecdsa.ts","../src/eddsa.ts","../src/mldsa.ts","../src/hmac.ts","../src/algorithm.ts","../src/headers.ts","../src/key.ts","../src/signature.ts","../src/resolve.ts","../src/asn1.ts","../src/x509.ts","../src/x5chain.ts","../src/sign1.ts","../src/sign.ts","../src/mac0.ts","../src/aes.ts","../src/recipient.ts","../src/mac.ts","../src/encrypt.ts"],"names":["cbor","curve","algorithm","IMPLEMENTED","implementationOf","nobleHmac","stated","bytesEqual","SIGNATURE_CONTEXT","requireSymmetric"],"mappings":";;;;;;;;;;;;;;AAkBO,IAAM,SAAA,GAAN,cAAwB,KAAA,CAAM;AAAA,EAER,IAAA,GAAO,WAAA;AAAA,EAEzB,WAAA,CAAY,SAAiB,OAAA,EAAwB;AACxD,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AAAA,EAC1B;AAEJ;AAiBO,IAAM,QAAA,GAAyB,EAAE,QAAA,EAAU,IAAA;AAc3C,IAAM,cAAc,CAAC,MAAA,MACvB,EAAE,QAAA,EAAU,OAAO,MAAA,EAAO;AAmBxB,IAAM,eAAe,CAAC,MAAA,MACxB,EAAE,SAAA,EAAW,OAAO,MAAA,EAAO;AC7BzB,IAAM,QAAA,GAAW,E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,EAAA,MAAM,KAAA,GAAQ,GAAA,CAAI,eAAA,EAAgB,CAAE,MAAA;AAEpC,EAAA,IAAIA,UAAAA,CAAU,OAAA,KAAY,IAAA,IAAQ,KAAA,KAAUA,UAAAA,CAAU,OAAA;AAClD,IAAA,MAAM,IAAI,SAAA,CAAU,CAAA,eAAA,EAAkBA,UAAAA,CAAU,IAAI,CAAA,UAAA,EAAa,MAAA,CAAOA,UAAAA,CAAU,OAAO,CAAC,CAAA,iBAAA,EAAoB,MAAA,CAAO,KAAK,CAAC,CAAA,oBAAA,CAAsB,CAAA;AAEzJ","file":"index.js","sourcesContent":["/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * What goes wrong, and the difference between the two kinds of wrong.\r\n *\r\n * A malformed message is a programming or transport error and throws. A\r\n * signature that does not verify is neither: it is the expected outcome of\r\n * checking untrusted data, and a library that throws for it invites the\r\n * `catch {}` that swallows the distinction. Verification therefore returns a\r\n * result that has to be looked at, and says why when the answer is no.\r\n */\r\n\r\n\r\n/** A COSE message, key or header bucket that is not well formed. */\r\nexport class CoseError extends Error {\r\n\r\n public override readonly name = 'CoseError';\r\n\r\n public constructor(message: string, options?: ErrorOptions) {\r\n super(message, options);\r\n }\r\n\r\n}\r\n\r\n\r\n/**\r\n * The outcome of a verification.\r\n *\r\n * `verified: false` carries a reason, because \"it did not verify\" is rarely\r\n * the useful half of the answer — whether the algorithm was refused, the\r\n * payload was missing or the signature itself was wrong are three very\r\n * different situations.\r\n */\r\nexport type Verification =\r\n | { readonly verified: true }\r\n | { readonly verified: false; readonly reason: string };\r\n\r\n\r\n/** A successful verification. */\r\nexport const VERIFIED: Verification = { verified: true };\r\n\r\n\r\n/**\r\n * A verification that failed.\r\n *\r\n * Named because it is the half of {@link Verification} that carries a reason,\r\n * and a function returning only this half lets a caller pass it straight on as\r\n * its own failure without the type widening back to \"or it succeeded\".\r\n */\r\nexport type NotVerified = Extract<Verification, { verified: false }>;\r\n\r\n\r\n/** A failed verification, with the reason it failed. */\r\nexport const notVerified = (reason: string): NotVerified =>\r\n ({ verified: false, reason });\r\n\r\n\r\n/**\r\n * The outcome of a decryption.\r\n *\r\n * Kept apart from {@link Verification} because the useful half is different: a\r\n * verification yields a yes or a no, a decryption yields the plaintext or a\r\n * reason. Note that there is no partial plaintext in the failure case and\r\n * never can be — an AEAD failure means the whole message is unauthenticated,\r\n * and handing back what was decrypted before the tag was checked is the classic\r\n * way to build an oracle out of a decryptor.\r\n */\r\nexport type Decryption =\r\n | { readonly decrypted: true; readonly plaintext: Uint8Array }\r\n | { readonly decrypted: false; readonly reason: string };\r\n\r\n\r\n/** A failed decryption, with the reason it failed. */\r\nexport const notDecrypted = (reason: string): Extract<Decryption, { decrypted: false }> =>\r\n ({ decrypted: false, reason });\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * The one seam between this COSE implementation and a CBOR codec.\r\n *\r\n * COSE is a thin layer over CBOR, and everything delicate about it is a\r\n * question of exact bytes: what a signature covers, whether an empty protected\r\n * bucket is `h''` or `h'A0'`, whether a map keeps the order it arrived in.\r\n * Keeping the codec behind a single module means those questions are answered\r\n * in one place — and it means where the codec comes from is one line rather\r\n * than a hundred imports.\r\n *\r\n * That line names the published `@vanaheimr/metrological-cbor`, an ordinary\r\n * dependency pinned by the lock file. It was a sibling checkout until the\r\n * codec's first release; the one arrangement that still builds both sides\r\n * from source is the cross-signing conformance suite, whose job is exactly\r\n * that — what it signs has to be what the codec produces *today* — and which\r\n * has its own repository and its own checkout layout for it. Here, drift\r\n * arrives the way it does for every consumer: as a release, which the nightly\r\n * installs the day it appears.\r\n *\r\n * The codec is the one from Metrological CBOR, which is a deterministic\r\n * encoder by default — and that default is wrong here. A COSE message is\r\n * somebody else's bytes: its header maps are in the order the signer wrote\r\n * them, and re-sorting them on the way out would invalidate signatures this\r\n * implementation never touched. Every encode below therefore passes\r\n * `PRESERVE`, and the one place that does not is the RFC 9679 thumbprint,\r\n * where deterministic encoding is what the specification asks for.\r\n */\r\n\r\nexport { cbor } from '@vanaheimr/metrological-cbor';\r\nexport type { CborValue } from '@vanaheimr/metrological-cbor';\r\n\r\nimport { cbor } from '@vanaheimr/metrological-cbor';\r\nimport type { CborValue } from '@vanaheimr/metrological-cbor';\r\n\r\n\r\n/** One entry of a CBOR map. */\r\nexport type CborEntry = readonly [CborValue, CborValue];\r\n\r\n\r\n/**\r\n * Encoder options for reproducing foreign bytes: no sorting, no float\r\n * re-widening. What was read is what is written.\r\n */\r\nexport const PRESERVE = { mapKeys: 'preserve', floats: 'preserve' } as const;\r\n\r\n\r\n/**\r\n * Encoder options for the deterministic encoding of RFC 8949 Section 4.2.1,\r\n * which RFC 9679 requires for a COSE Key Thumbprint.\r\n */\r\nexport const DETERMINISTIC = { mapKeys: 'sorted', floats: 'shortest' } as const;\r\n\r\n\r\n/** Encode a value as the bytes of a COSE message or structure. */\r\nexport const encode = (value: CborValue): Uint8Array =>\r\n cbor.encode(value, PRESERVE);\r\n\r\n\r\n/**\r\n * Decode the bytes of a COSE message.\r\n *\r\n * Deliberately not in strict mode: a COSE message arrives from the wire and\r\n * has to be read as it is. Rejecting a message because its unprotected bucket\r\n * is not in deterministic order would refuse messages that are perfectly valid\r\n * COSE — and would refuse them *after* the signature over the protected part\r\n * would have verified.\r\n */\r\nexport const decode = (data: Uint8Array): CborValue =>\r\n cbor.decode(data, { strict: false });\r\n\r\n\r\n/** Whether two byte strings are equal. */\r\nexport function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\r\n\r\n if (left.length !== right.length)\r\n return false;\r\n\r\n for (let index = 0; index < left.length; index++) {\r\n if (left[index] !== right[index])\r\n return false;\r\n }\r\n\r\n return true;\r\n\r\n}\r\n\r\n\r\n/** The empty byte string, which COSE uses rather more often than one expects. */\r\nexport const NO_BYTES = new Uint8Array();\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * The payload of a COSE message is an opaque byte string: RFC 9052 says\r\n * nothing about what is inside it, and a signature covers those bytes rather\r\n * than their meaning.\r\n *\r\n * This module is about the one thing an application very often does want said\r\n * about it — that it is CBOR, and that it is written in the deterministic\r\n * encoding of RFC 8949 Section 4.2.1. The reason is not tidiness but\r\n * forwarding. A receiver that parses a signed record and serializes it again\r\n * gets the bytes *its* encoder produces — map entries sorted, heads at their\r\n * shortest, no indefinite lengths — and not the bytes it was handed. Where the\r\n * signer wrote a different spelling of the same data, the forwarded signature\r\n * no longer verifies, and nothing in the message says why: a signature cannot\r\n * tell being tampered with from being retyped.\r\n *\r\n * Signing the deterministic encoding removes the second spelling. There is\r\n * then one way to write the record down, and everybody who parses and\r\n * re-encodes it arrives at the very bytes the signature covers.\r\n *\r\n * The Styx counterpart is `Illias/COSE/COSEPayload.cs`, and the conformance\r\n * suite signs the same non-canonical payload with both.\r\n */\r\n\r\nimport { bytesEqual, cbor, DETERMINISTIC } from './cbor.ts';\r\n\r\n\r\n/**\r\n * Rewrite a payload in the deterministic encoding of RFC 8949 Section 4.2.1,\r\n * or return it unchanged where it is not one well-formed CBOR data item and\r\n * nothing else.\r\n *\r\n * Not being CBOR is not an error here: text, JSON, an image or a detached\r\n * hash have no canonical CBOR form to be rewritten into, and a COSE payload is\r\n * allowed to be any of them.\r\n */\r\nexport function canonicalizePayload(payload: Uint8Array): Uint8Array {\r\n\r\n try {\r\n // Decoded leniently on purpose: the non-deterministic spelling is\r\n // exactly what this function exists to accept and rewrite. Reading it\r\n // strictly would refuse the only input it can help with.\r\n return cbor.encode(cbor.decode(payload, { strict: false }), DETERMINISTIC);\r\n }\r\n catch {\r\n return payload;\r\n }\r\n\r\n}\r\n\r\n\r\n/**\r\n * Whether a payload survives being decoded and encoded again: whether it is\r\n * one well-formed CBOR data item whose deterministic encoding is the payload\r\n * itself.\r\n *\r\n * Deliberately the round trip rather than a strict decode. What a forwarding\r\n * receiver actually does is decode and re-encode, so the question worth\r\n * answering is whether that changes anything — not whether a list of rules is\r\n * satisfied.\r\n *\r\n * A payload that is not CBOR is not canonical: there is nothing here to have\r\n * an opinion about.\r\n */\r\nexport function isCanonicalPayload(payload: Uint8Array): boolean {\r\n\r\n try {\r\n return bytesEqual(cbor.encode(cbor.decode(payload, { strict: false }), DETERMINISTIC),\r\n payload);\r\n }\r\n catch {\r\n return false;\r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * COSE header parameter labels [RFC 9052, Section 3.1].\r\n *\r\n * These are the labels of a *header bucket*, and they are not the labels of a\r\n * COSE key: label 3 is the content type here and the algorithm there, label 4\r\n * is the key identifier here and the key operations there. The two sets live\r\n * in separate modules for exactly that reason.\r\n */\r\n\r\nimport { cbor } from './cbor.ts';\r\nimport type { CborValue } from './cbor.ts';\r\n\r\n\r\n/** The header parameter labels this implementation knows by name. */\r\nexport const HeaderLabel = {\r\n\r\n /** The cryptographic algorithm [RFC 9052]. */\r\n algorithm: 1,\r\n\r\n /** The labels a recipient is required to understand [RFC 9052]. */\r\n critical: 2,\r\n\r\n /** The content type of the payload [RFC 9052]. */\r\n contentType: 3,\r\n\r\n /** The key identifier [RFC 9052]. */\r\n keyIdentifier: 4,\r\n\r\n /** The initialization vector [RFC 9052]. */\r\n iv: 5,\r\n\r\n /** The partial initialization vector [RFC 9052]. */\r\n partialIv: 6,\r\n\r\n /** The countersignature of RFC 8152, superseded by label 11 [RFC 9338]. */\r\n counterSignature: 7,\r\n\r\n /** The countersignature that also covers the signature it signs [RFC 9338]. */\r\n counterSignatureV2: 11,\r\n\r\n /** The abbreviated countersignature, not implemented here [RFC 9338]. */\r\n counterSignature0V2: 12,\r\n\r\n /** An unordered bag of X.509 certificates [RFC 9360]. */\r\n x5Bag: 32,\r\n\r\n /** An ordered X.509 certificate chain [RFC 9360]. */\r\n x5Chain: 33,\r\n\r\n /** The hash of an X.509 certificate [RFC 9360]. */\r\n x5T: 34,\r\n\r\n /** A URI naming an X.509 certificate [RFC 9360]. */\r\n x5U: 35,\r\n\r\n} as const;\r\n\r\n\r\n/** A header parameter label as it travels: an integer, or a text string. */\r\nexport const label = (value: number): CborValue =>\r\n cbor.int(value);\r\n\r\n\r\n/**\r\n * The name of a header parameter label, for error messages.\r\n */\r\nexport function headerLabelName(value: CborValue): string {\r\n\r\n if (value.type === 'int') {\r\n\r\n switch (value.value) {\r\n case 1n: return 'alg';\r\n case 2n: return 'crit';\r\n case 3n: return 'content type';\r\n case 4n: return 'kid';\r\n case 5n: return 'IV';\r\n case 6n: return 'Partial IV';\r\n case 7n: return 'counter signature';\r\n case 11n: return 'counter signature version 2';\r\n case 12n: return 'counter signature 0 version 2';\r\n case 32n: return 'x5bag';\r\n case 33n: return 'x5chain';\r\n case 34n: return 'x5t';\r\n case 35n: return 'x5u';\r\n }\r\n\r\n }\r\n\r\n if (value.type === 'text')\r\n return value.value;\r\n\r\n return cbor.diagnostic(value);\r\n\r\n}\r\n\r\n\r\n/**\r\n * Whether this implementation understands and processes the given header\r\n * parameter, which is what the `crit` header parameter asks about\r\n * [RFC 9052, Section 3.1].\r\n *\r\n * Four labels, and deliberately not the X.509 ones. Whether a certificate\r\n * chain has been *understood* is a property of the verification being\r\n * performed rather than of the library: whoever verifies with a bare public\r\n * key has not looked at any certificate and must not claim otherwise. Callers\r\n * that do process one say so per call, through `alsoUnderstood`.\r\n */\r\nexport function isUnderstood(value: CborValue): boolean {\r\n\r\n return value.type === 'int' &&\r\n (value.value === 1n || value.value === 2n ||\r\n value.value === 3n || value.value === 4n);\r\n\r\n}\r\n\r\n\r\n/** Whether two header parameter labels are the same label. */\r\nexport function sameLabel(left: CborValue, right: CborValue): boolean {\r\n\r\n if (left.type === 'int' && right.type === 'int')\r\n return left.value === right.value;\r\n\r\n if (left.type === 'text' && right.type === 'text')\r\n return left.value === right.value;\r\n\r\n return false;\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * The COSE elliptic curve registry [IANA, \"COSE Elliptic Curves\"].\r\n *\r\n * Two widths are recorded per curve and they are kept apart on purpose: the\r\n * *field* size is the width of a coordinate, the *order* size is the width of\r\n * a private key and of each half of an ECDSA signature. They coincide for\r\n * every curve in this registry, and they are still two different quantities —\r\n * a curve where they differ would silently produce keys other implementations\r\n * reject.\r\n *\r\n * P-521 is 66 bytes, not 64 and not 65. Its field is 521 bits wide, which is\r\n * 65 bytes and one bit.\r\n */\r\n\r\n\r\n/** A curve in the COSE registry. */\r\nexport interface CoseCurve {\r\n\r\n /** The IANA identifier, as it travels in a COSE key. */\r\n readonly id: number;\r\n\r\n /** The registered name, e.g. `P-256`. Case sensitive. */\r\n readonly name: string;\r\n\r\n /** The key type this curve belongs to: 2 = EC2, 1 = OKP. */\r\n readonly keyType: number;\r\n\r\n /**\r\n * On an EC2 curve, the width of one coordinate. On an OKP curve, the width\r\n * of the public key, which is the whole of `x` — there is no `y`.\r\n */\r\n readonly fieldSize: number | null;\r\n\r\n /**\r\n * On an EC2 curve, the width of a private key and of each half of a\r\n * signature. On an OKP curve, the width of the private key.\r\n *\r\n * Ed448 is 57 bytes and not 56: RFC 8032 appends a sign bit to the 456-bit\r\n * encoding, which costs a whole further octet.\r\n */\r\n readonly orderSize: number | null;\r\n\r\n}\r\n\r\n\r\nconst curve = (id: number, name: string, keyType: number,\r\n fieldSize: number | null, orderSize: number | null): CoseCurve =>\r\n ({ id, name, keyType, fieldSize, orderSize });\r\n\r\n\r\n/** Key type 2, elliptic curve keys with x and y coordinates [RFC 9052, Section 7]. */\r\nexport const KEY_TYPE_EC2 = 2;\r\n\r\n/** Key type 1, octet key pairs [RFC 9052, Section 7]. */\r\nexport const KEY_TYPE_OKP = 1;\r\n\r\n\r\n/** The curves this implementation knows by name. */\r\nexport const CoseCurves = {\r\n\r\n P256: curve( 1, 'P-256', KEY_TYPE_EC2, 32, 32),\r\n P384: curve( 2, 'P-384', KEY_TYPE_EC2, 48, 48),\r\n P521: curve( 3, 'P-521', KEY_TYPE_EC2, 66, 66),\r\n // The two key-agreement curves carry no signature algorithm, so their\r\n // widths are recorded as unknown rather than guessed at.\r\n X25519: curve( 4, 'X25519', KEY_TYPE_OKP, null, null),\r\n X448: curve( 5, 'X448', KEY_TYPE_OKP, null, null),\r\n\r\n Ed25519: curve( 6, 'Ed25519', KEY_TYPE_OKP, 32, 32),\r\n Ed448: curve( 7, 'Ed448', KEY_TYPE_OKP, 57, 57),\r\n secp256k1: curve( 8, 'secp256k1', KEY_TYPE_EC2, 32, 32),\r\n\r\n // Registered by ISO/IEC 18013-5 for the mobile driving licence.\r\n brainpoolP256r1: curve(256, 'brainpoolP256r1', KEY_TYPE_EC2, 32, 32),\r\n brainpoolP320r1: curve(257, 'brainpoolP320r1', KEY_TYPE_EC2, 40, 40),\r\n brainpoolP384r1: curve(258, 'brainpoolP384r1', KEY_TYPE_EC2, 48, 48),\r\n brainpoolP512r1: curve(259, 'brainpoolP512r1', KEY_TYPE_EC2, 64, 64),\r\n\r\n} as const;\r\n\r\n\r\n/** Every registered curve, in registry order. */\r\nexport const ALL_CURVES: readonly CoseCurve[] = Object.values(CoseCurves);\r\n\r\n\r\n/** The curve with the given identifier, or null when it is not registered. */\r\nexport function curveById(id: number): CoseCurve | null {\r\n return ALL_CURVES.find(each => each.id === id) ?? null;\r\n}\r\n\r\n\r\n/**\r\n * The curve with the given name, or null.\r\n *\r\n * Case sensitive, like the registry: `p-256` is not `P-256`.\r\n */\r\nexport function curveByName(name: string): CoseCurve | null {\r\n return ALL_CURVES.find(each => each.name === name) ?? null;\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * The second and last seam: everything that computes a hash or touches a\r\n * private key lives here.\r\n *\r\n * Two things about ECDSA in COSE are easy to get wrong and both are settled in\r\n * this module.\r\n *\r\n * **The signature is `r ‖ s`, not DER.** Each component is zero-padded to the\r\n * width of the group order [RFC 9053, Section 2.1] — 64 bytes on P-256, 132 on\r\n * P-521. Most general-purpose signing APIs hand out DER by default, and a DER\r\n * signature in a COSE message fails verification everywhere with an error that\r\n * looks like a bad encoder.\r\n *\r\n * **Low-S normalization is a policy, not a rule.** Every ECDSA signature has a\r\n * valid twin `(r, n − s)`, and several libraries reject the second by default\r\n * under the anti-malleability convention Bitcoin established. COSE imposes no\r\n * such thing, and a meter that signs without normalizing produces perfectly\r\n * valid signatures that a low-S verifier refuses. Verification here therefore\r\n * passes `lowS: false`, which accepts both forms.\r\n *\r\n * Signing is deterministic (RFC 6979): the nonce is derived from the private\r\n * key and the message rather than drawn at random. That makes a published\r\n * example recomputable, and it matters rather more for a device with no\r\n * dependable source of randomness, where a repeated nonce hands over the\r\n * private key.\r\n */\r\n\r\nimport { ecdsa, weierstrass } from '@noble/curves/abstract/weierstrass.js';\r\nimport { sha256, sha384, sha512 } from '@noble/hashes/sha2.js';\r\nimport type { CHash } from '@noble/hashes/utils.js';\r\nimport { p256, p384, p521 } from '@noble/curves/nist.js';\r\nimport { brainpoolP256r1, brainpoolP384r1,\r\n brainpoolP512r1 } from '@noble/curves/misc.js';\r\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\r\n\r\nimport { CoseError } from './errors.ts';\r\nimport type { CoseCurve } from './curve.ts';\r\n\r\n\r\n/**\r\n * brainpoolP320r1 [RFC 5639, Section 3.4].\r\n *\r\n * The one curve of the COSE registry the underlying library does not ship —\r\n * the three other brainpool curves it does — so it is defined here from its\r\n * published domain parameters. Nothing about that is exotic: a Weierstrass\r\n * curve *is* these seven numbers, and the library's own brainpool definitions\r\n * are written exactly this way.\r\n *\r\n * Transcribing 320-bit constants is the kind of task that fails silently, so\r\n * they are checked three times over: `weierstrass()` refuses a generator that\r\n * is not on the curve, `tests/brainpool.test.ts` checks that the order really\r\n * is the order, and the conformance suite signs with them and compares the\r\n * bytes against Bouncy Castle's own brainpoolP320r1. A single wrong digit\r\n * survives none of the three.\r\n *\r\n * SHA-384 goes with a 320-bit curve, which looks like a mistake and is what\r\n * RFC 9864 registers for `ESB320`. It matters twice over here: it is the\r\n * message digest, and it is the hash the RFC 6979 nonce is derived with.\r\n */\r\nconst brainpoolP320r1 = /* @__PURE__ */ ecdsa(weierstrass({\r\n p: BigInt('0xd35e472036bc4fb7e13c785ed201e065f98fcfa6f6f40def4f92b9ec7893ec28fcd412b1f1b32e27'),\r\n a: BigInt('0x3ee30b568fbab0f883ccebd46d3f3bb8a2a73513f5eb79da66190eb085ffa9f492f375a97d860eb4'),\r\n b: BigInt('0x520883949dfdbc42d3ad198640688a6fe13f41349554b49acc31dccd884539816f5eb4ac8fb1f1a6'),\r\n n: BigInt('0xd35e472036bc4fb7e13c785ed201e065f98fcfa5b68f12a32d482ec7ee8658e98691555b44c59311'),\r\n Gx: BigInt('0x43bd7e9afb53d8b85289bcc48ee5bfe6f20137d10a087eb6e7871e2a10a599c710af8d0d39e20611'),\r\n Gy: BigInt('0x14fdd05545ec1cc8ab4093247f77275e0743ffed117182eaa9c77877aaac6ac7d35245d1692e8ee1'),\r\n h: BigInt(1),\r\n}), sha384);\r\n\r\n\r\n/** The digest algorithms COSE signature algorithms use. */\r\nexport type DigestAlgorithm = 'sha256' | 'sha384' | 'sha512';\r\n\r\n/** The implementation behind each digest name — shared with the HMAC in `hmac.ts`. */\r\nexport const HASHES: Record<DigestAlgorithm, CHash> = { sha256, sha384, sha512 };\r\n\r\n\r\n/** What this module needs from an elliptic curve implementation. */\r\ninterface EcdsaCurve {\r\n sign(message: Uint8Array, privateKey: Uint8Array,\r\n options?: { prehash?: boolean; lowS?: boolean }): Uint8Array;\r\n verify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array,\r\n options?: { prehash?: boolean; lowS?: boolean }): boolean;\r\n getPublicKey(privateKey: Uint8Array, isCompressed?: boolean): Uint8Array;\r\n Point: {\r\n fromBytes(bytes: Uint8Array): { toBytes(isCompressed: boolean): Uint8Array };\r\n };\r\n}\r\n\r\n\r\n/**\r\n * The curves this build can compute with, by COSE curve name — which is every\r\n * EC2 curve the COSE registry has.\r\n */\r\nconst IMPLEMENTED: Readonly<Record<string, EcdsaCurve>> = {\r\n 'P-256': p256,\r\n 'P-384': p384,\r\n 'P-521': p521,\r\n 'secp256k1': secp256k1,\r\n 'brainpoolP256r1': brainpoolP256r1,\r\n 'brainpoolP320r1': brainpoolP320r1,\r\n 'brainpoolP384r1': brainpoolP384r1,\r\n 'brainpoolP512r1': brainpoolP512r1,\r\n};\r\n\r\n\r\n/** Whether this build can sign and verify on the given curve. */\r\nexport const isImplemented = (curve: CoseCurve): boolean =>\r\n curve.name in IMPLEMENTED;\r\n\r\n\r\nfunction implementationOf(curve: CoseCurve): EcdsaCurve {\r\n\r\n const implementation = IMPLEMENTED[curve.name];\r\n\r\n if (implementation === undefined)\r\n throw new CoseError(`The elliptic curve '${curve.name}' is registered by COSE, but this build does not implement it!`);\r\n\r\n return implementation;\r\n\r\n}\r\n\r\n\r\n/** The message digest an algorithm signs over. */\r\nexport const digest = (algorithm: DigestAlgorithm, data: Uint8Array): Uint8Array =>\r\n HASHES[algorithm](data);\r\n\r\n\r\n/**\r\n * Sign the given digest, returning the COSE wire form `r ‖ s`.\r\n *\r\n * `prehash: false` says the input already *is* the digest — the caller hashed\r\n * the Sig_structure, because which digest to use is a property of the COSE\r\n * algorithm rather than of the curve.\r\n *\r\n * `lowS: false` is the load-bearing one. The underlying library normalizes `s`\r\n * to its low form by default, and COSE does not: RFC 6979 publishes the\r\n * un-normalized values, and so does every implementation that follows it. With\r\n * normalization on, this library would produce signatures that verify\r\n * everywhere and are nevertheless *different bytes* from the ones the C#\r\n * reference implementation produces for the same key and the same message —\r\n * which would quietly destroy the one property that makes a deterministic\r\n * signature worth having.\r\n */\r\nexport function sign(curve: CoseCurve,\r\n messageHash: Uint8Array,\r\n privateKey: Uint8Array): Uint8Array {\r\n\r\n return implementationOf(curve).sign(messageHash, privateKey,\r\n { prehash: false, lowS: false });\r\n\r\n}\r\n\r\n\r\n/**\r\n * Verify a `r ‖ s` signature over the given digest.\r\n *\r\n * A signature of the wrong width is refused before it reaches the curve, with\r\n * an error that names the likely cause: nearly every such signature is a DER\r\n * encoding that was never converted.\r\n */\r\nexport function verify(curve: CoseCurve,\r\n signature: Uint8Array,\r\n messageHash: Uint8Array,\r\n publicKey: Uint8Array): boolean {\r\n\r\n const expected = (curve.orderSize ?? 0) * 2;\r\n\r\n if (signature.length !== expected)\r\n throw new CoseError(`An ECDSA signature on the curve '${curve.name}' must be ${expected} bytes wide — the concatenated components r and s, each zero-padded to the width of the group order [RFC 9053, Section 2.1] — but was ${signature.length} bytes wide. A signature of a length such as this one is usually a DER encoding that was never converted!`);\r\n\r\n try {\r\n return implementationOf(curve).verify(signature, messageHash, publicKey,\r\n { prehash: false, lowS: false });\r\n }\r\n catch {\r\n // A public key that is not on the curve, or a component out of range.\r\n // Untrusted input is allowed to be nonsense; it is not a verification.\r\n return false;\r\n }\r\n\r\n}\r\n\r\n\r\n/**\r\n * The uncompressed public key `04 ‖ x ‖ y` belonging to a private key.\r\n */\r\nexport function publicKeyFor(curve: CoseCurve, privateKey: Uint8Array): Uint8Array {\r\n return implementationOf(curve).getPublicKey(privateKey, false);\r\n}\r\n\r\n\r\n/**\r\n * Recover the y coordinate of a point from its x coordinate and the parity of\r\n * its y [RFC 9052, Section 7.1.1].\r\n *\r\n * A COSE key may carry `y` as a boolean rather than as a byte string, which\r\n * halves the size of the key. There are two points with any given x, and the\r\n * boolean says which of the two: the sign bit is the parity of y.\r\n */\r\nexport function decompressY(curve: CoseCurve, x: Uint8Array, oddY: boolean): Uint8Array {\r\n\r\n const fieldSize = curve.fieldSize ?? 0;\r\n const compressed = new Uint8Array(1 + x.length);\r\n\r\n compressed[0] = oddY ? 0x03 : 0x02;\r\n compressed.set(x, 1);\r\n\r\n const uncompressed = implementationOf(curve).Point.fromBytes(compressed).toBytes(false);\r\n\r\n return uncompressed.slice(1 + fieldSize);\r\n\r\n}\r\n\r\n\r\n/**\r\n * Whether the point `04 ‖ x ‖ y` lies on the curve.\r\n *\r\n * A public key that does not is not merely useless: handing one to a\r\n * verification is how invalid-curve attacks start.\r\n */\r\nexport function isOnCurve(curve: CoseCurve, uncompressed: Uint8Array): boolean {\r\n\r\n try {\r\n implementationOf(curve).Point.fromBytes(uncompressed);\r\n return true;\r\n }\r\n catch {\r\n return false;\r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * EdDSA [RFC 8032], as COSE uses it [RFC 9053, Section 2.2].\r\n *\r\n * The difference from ECDSA that matters here is that there is **no separate\r\n * digest**. PureEdDSA hashes the message itself, twice, as part of signing, so\r\n * the Sig_structure goes to the signer whole. Handing it a SHA-512 digest\r\n * instead would produce a signature that is perfectly valid for the *digest*\r\n * and that no other implementation would ever accept.\r\n *\r\n * The second difference is a gift: EdDSA is deterministic by construction. The\r\n * nonce is derived from the private key and the message [RFC 8032, Section\r\n * 5.1.6], with no option to draw it at random, so two implementations signing\r\n * the same bytes with the same key necessarily produce the same signature. The\r\n * cross-signing suite compares those bytes without needing any of the\r\n * arrangements ECDSA needs.\r\n *\r\n * Keys are octet key pairs (kty = OKP): a public key is the whole of `x`, and\r\n * there is no `y` to go with it.\r\n */\r\n\r\nimport { ed25519 } from '@noble/curves/ed25519.js';\r\nimport { ed448 } from '@noble/curves/ed448.js';\r\n\r\nimport { CoseCurves } from './curve.ts';\r\nimport type { CoseCurve } from './curve.ts';\r\nimport { CoseError } from './errors.ts';\r\n\r\n\r\n/** What this module needs from an EdDSA implementation. */\r\ninterface EddsaCurve {\r\n sign(message: Uint8Array, privateKey: Uint8Array): Uint8Array;\r\n verify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean;\r\n getPublicKey(privateKey: Uint8Array): Uint8Array;\r\n}\r\n\r\n\r\nconst IMPLEMENTED: Readonly<Record<string, EddsaCurve>> = {\r\n 'Ed25519': ed25519,\r\n 'Ed448': ed448,\r\n};\r\n\r\n\r\n/** Whether this build can sign and verify on the given EdDSA curve. */\r\nexport const isEddsaCurve = (curve: CoseCurve): boolean =>\r\n curve.name in IMPLEMENTED;\r\n\r\n\r\nfunction implementationOf(curve: CoseCurve): EddsaCurve {\r\n\r\n const implementation = IMPLEMENTED[curve.name];\r\n\r\n if (implementation === undefined)\r\n throw new CoseError(`The curve '${curve.name}' is not an EdDSA signature curve this implementation supports!`);\r\n\r\n return implementation;\r\n\r\n}\r\n\r\n\r\n/** The signature width of an EdDSA curve, in bytes. */\r\nexport function eddsaSignatureSize(curve: CoseCurve): number {\r\n\r\n if (curve.id === CoseCurves.Ed25519.id) return 64;\r\n if (curve.id === CoseCurves.Ed448.id) return 114;\r\n\r\n throw new CoseError(`The curve '${curve.name}' has no EdDSA signature size!`);\r\n\r\n}\r\n\r\n\r\n/**\r\n * Sign the Sig_structure itself — not a digest of it.\r\n */\r\nexport function eddsaSign(curve: CoseCurve,\r\n message: Uint8Array,\r\n privateKey: Uint8Array): Uint8Array {\r\n\r\n return implementationOf(curve).sign(message, privateKey);\r\n\r\n}\r\n\r\n\r\n/** Verify an EdDSA signature over the Sig_structure. */\r\nexport function eddsaVerify(curve: CoseCurve,\r\n signature: Uint8Array,\r\n message: Uint8Array,\r\n publicKey: Uint8Array): boolean {\r\n\r\n const expected = eddsaSignatureSize(curve);\r\n\r\n if (signature.length !== expected)\r\n throw new CoseError(`An EdDSA signature on the curve '${curve.name}' must be ${String(expected)} bytes wide, but was ${String(signature.length)} bytes wide!`);\r\n\r\n try {\r\n return implementationOf(curve).verify(signature, message, publicKey);\r\n }\r\n catch {\r\n // A public key that is not a valid point, or a malformed signature.\r\n // Untrusted input is allowed to be nonsense; it is not a verification.\r\n return false;\r\n }\r\n\r\n}\r\n\r\n\r\n/** The public key belonging to an EdDSA private key. */\r\nexport function eddsaPublicKeyFor(curve: CoseCurve, privateKey: Uint8Array): Uint8Array {\r\n return implementationOf(curve).getPublicKey(privateKey);\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * ML-DSA [FIPS 204], as COSE uses it [RFC 9964].\r\n *\r\n * The post-quantum signature scheme, and the one place in this library where\r\n * the numbers stop being small: a ML-DSA-87 signature is 4627 bytes over a\r\n * metrological reading of about thirty. That ratio is an argument for CBOR\r\n * rather than against ML-DSA — base64 in JSON would add a third again to the\r\n * largest field in the message, and a byte string in CBOR costs two or three\r\n * bytes of head and nothing else.\r\n *\r\n * Three things about it differ from every other algorithm here.\r\n *\r\n * **It is pure.** Algorithm 2 of FIPS 204 takes the message, not a digest of\r\n * it, exactly as EdDSA does.\r\n *\r\n * **The private key is the 32-byte seed**, not the expanded secret key. RFC\r\n * 9964 requires it: \"the `priv` parameter MUST be the seed and MUST have a\r\n * length of 32 bytes\". The expanded key is derived here on every use, which is\r\n * the price of a key that is 32 bytes on the wire instead of up to 4896.\r\n *\r\n * **Signing is randomized by default**, and the specification does not say it\r\n * must not be. FIPS 204 also defines a deterministic variant, in which the\r\n * per-signature randomness is 32 zero bytes; this module always uses it. Two\r\n * implementations that both do so produce identical signature bytes, which is\r\n * what lets the cross-signing suite compare them rather than merely check that\r\n * each accepts the other's.\r\n */\r\n\r\nimport { ml_dsa44, ml_dsa65, ml_dsa87 } from '@noble/post-quantum/ml-dsa.js';\r\n\r\nimport { CoseError } from './errors.ts';\r\n\r\n\r\n/** What this module needs from an ML-DSA implementation. */\r\ninterface MldsaScheme {\r\n keygen(seed: Uint8Array): { publicKey: Uint8Array; secretKey: Uint8Array };\r\n sign(message: Uint8Array, secretKey: Uint8Array,\r\n options?: { extraEntropy?: Uint8Array | false }): Uint8Array;\r\n verify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean;\r\n}\r\n\r\n\r\n/** The three parameter sets RFC 9964 registers. */\r\nexport const MLDSA_PARAMETER_SETS = ['ML-DSA-44', 'ML-DSA-65', 'ML-DSA-87'] as const;\r\n\r\nexport type MldsaParameterSet = typeof MLDSA_PARAMETER_SETS[number];\r\n\r\n\r\nconst IMPLEMENTED: Readonly<Record<string, MldsaScheme>> = {\r\n 'ML-DSA-44': ml_dsa44,\r\n 'ML-DSA-65': ml_dsa65,\r\n 'ML-DSA-87': ml_dsa87,\r\n};\r\n\r\n\r\n/** The sizes RFC 9964 prints, in bytes. */\r\nexport const MLDSA_SIZES: Readonly<Record<MldsaParameterSet,\r\n { publicKey: number; signature: number }>> = {\r\n 'ML-DSA-44': { publicKey: 1312, signature: 2420 },\r\n 'ML-DSA-65': { publicKey: 1952, signature: 3309 },\r\n 'ML-DSA-87': { publicKey: 2592, signature: 4627 },\r\n};\r\n\r\n\r\n/** The length of an ML-DSA private key, which is always the seed. */\r\nexport const MLDSA_SEED_SIZE = 32;\r\n\r\n\r\nfunction schemeOf(parameterSet: string): MldsaScheme {\r\n\r\n const scheme = IMPLEMENTED[parameterSet];\r\n\r\n if (scheme === undefined)\r\n throw new CoseError(`'${parameterSet}' is not an ML-DSA parameter set this implementation supports!`);\r\n\r\n return scheme;\r\n\r\n}\r\n\r\n\r\n/** Whether the given name is a parameter set this build can compute with. */\r\nexport const isMldsaParameterSet = (parameterSet: string): parameterSet is MldsaParameterSet =>\r\n parameterSet in IMPLEMENTED;\r\n\r\n\r\n/**\r\n * The public key belonging to a seed.\r\n *\r\n * Deriving rather than storing it is what keeps `priv` at 32 bytes: the\r\n * expanded secret key of ML-DSA-87 is 4896.\r\n */\r\nexport function mldsaPublicKeyFor(parameterSet: string, seed: Uint8Array): Uint8Array {\r\n\r\n requireSeed(seed);\r\n\r\n return schemeOf(parameterSet).keygen(seed).publicKey;\r\n\r\n}\r\n\r\n\r\n/**\r\n * Sign the Sig_structure itself, deterministically.\r\n *\r\n * `extraEntropy: false` selects the deterministic variant of FIPS 204, in\r\n * which the per-signature randomness is 32 zero bytes rather than drawn.\r\n */\r\nexport function mldsaSign(parameterSet: string,\r\n message: Uint8Array,\r\n seed: Uint8Array): Uint8Array {\r\n\r\n requireSeed(seed);\r\n\r\n const scheme = schemeOf(parameterSet);\r\n\r\n return scheme.sign(message, scheme.keygen(seed).secretKey, { extraEntropy: false });\r\n\r\n}\r\n\r\n\r\n/** Verify an ML-DSA signature over the Sig_structure. */\r\nexport function mldsaVerify(parameterSet: string,\r\n signature: Uint8Array,\r\n message: Uint8Array,\r\n publicKey: Uint8Array): boolean {\r\n\r\n const sizes = isMldsaParameterSet(parameterSet) ? MLDSA_SIZES[parameterSet] : undefined;\r\n\r\n if (sizes !== undefined && signature.length !== sizes.signature)\r\n throw new CoseError(`An ${parameterSet} signature must be ${String(sizes.signature)} bytes wide, but was ${String(signature.length)} bytes wide!`);\r\n\r\n try {\r\n return schemeOf(parameterSet).verify(signature, message, publicKey);\r\n }\r\n catch {\r\n return false;\r\n }\r\n\r\n}\r\n\r\n\r\nfunction requireSeed(seed: Uint8Array): void {\r\n\r\n if (seed.length !== MLDSA_SEED_SIZE)\r\n throw new CoseError(`The private key of an ML-DSA COSE key is the seed and must be ${String(MLDSA_SEED_SIZE)} bytes long [RFC 9964], but was ${String(seed.length)} bytes long!`);\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * HMAC [RFC 2104], as COSE parameterizes it [RFC 9053, Section 3.1].\r\n *\r\n * A message authentication code is not a small signature, and the difference\r\n * is worth stating where the code lives. A MAC is **symmetric**: whoever can\r\n * verify one can produce one. It therefore answers \"did this come from someone\r\n * holding the key\", which is a question only a key holder can ask, and it\r\n * never answers \"did this come from *that* party\" to anybody else. A signature\r\n * does. That is why a metrological record is signed and not MACed — the\r\n * customer, the operator and the regulator all have to be able to check it,\r\n * and none of them may be able to forge it.\r\n *\r\n * What a MAC buys in return is size and speed: eight bytes and one pass of a\r\n * hash function, against sixty-four bytes and a curve multiplication for the\r\n * smallest signature here.\r\n *\r\n * Two things in this file exist only because of the symmetry, and both would\r\n * be pointless in the signature code beside it:\r\n *\r\n * - **The comparison is constant time.** A byte-by-byte compare that returns\r\n * early tells an attacker how many leading bytes of a guessed tag were\r\n * right, which turns forging a 32-byte tag from 2^256 work into 32 × 256.\r\n * Signature verification has no equivalent exposure, because everything it\r\n * compares is public.\r\n * - **Truncation is applied to the output**, never to the key: RFC 9053 keeps\r\n * \"the leftmost tag-length bits\" of the full HMAC.\r\n */\r\n\r\nimport { hmac as nobleHmac } from '@noble/hashes/hmac.js';\r\n\r\nimport { CoseError } from './errors.ts';\r\nimport { HASHES } from './ecdsa.ts';\r\nimport type { DigestAlgorithm } from './ecdsa.ts';\r\n\r\n\r\n/**\r\n * The full HMAC of a message, before any truncation.\r\n *\r\n * The key is passed through as it is. RFC 9053 says the key SHOULD be as long\r\n * as the hash output, which is a recommendation about key management rather\r\n * than a rule about the primitive — RFC 2104 accepts any length, and the\r\n * published test vectors of RFC 4231 include a four-byte key. Refusing short\r\n * keys here would make those vectors unreproducible while protecting nobody\r\n * who was not already choosing their own key length.\r\n */\r\nexport const hmac = (hash: DigestAlgorithm, key: Uint8Array, message: Uint8Array): Uint8Array =>\r\n nobleHmac(HASHES[hash], key, message);\r\n\r\n\r\n/**\r\n * The authentication tag of a message: the HMAC, truncated to the width the\r\n * algorithm names.\r\n *\r\n * `tagSize` is in bytes and is the algorithm's, never the caller's — the\r\n * whole point of `HMAC 256/64` being a registered identifier rather than a\r\n * parameter is that both parties know the width from the message.\r\n */\r\nexport function macTag(hash: DigestAlgorithm,\r\n tagSize: number,\r\n key: Uint8Array,\r\n message: Uint8Array): Uint8Array {\r\n\r\n const full = hmac(hash, key, message);\r\n\r\n if (tagSize > full.length)\r\n throw new CoseError(`An HMAC over ${hash} is ${String(full.length)} bytes long and can not be truncated to ${String(tagSize)}!`);\r\n\r\n return tagSize === full.length ? full : full.subarray(0, tagSize);\r\n\r\n}\r\n\r\n\r\n/**\r\n * Whether two authentication tags are the same, without saying *where* they\r\n * first differ.\r\n *\r\n * The length check in front is not a leak: the width of a tag follows from the\r\n * algorithm, which travels in the message and is known to everybody. What must\r\n * not leak is the position of the first differing byte, and that is what the\r\n * constant-time comparison protects.\r\n */\r\nexport function tagsEqual(left: Uint8Array, right: Uint8Array): boolean {\r\n\r\n if (left.length !== right.length)\r\n return false;\r\n\r\n // The classic accumulating XOR: every byte is visited whatever the data\r\n // says, and only the final OR of all differences decides. (The `?? 0` is\r\n // for the type checker alone; the loop bound keeps the index in range.)\r\n let difference = 0;\r\n\r\n for (let index = 0; index < left.length; index++)\r\n difference |= (left[index] ?? 0) ^ (right[index] ?? 0);\r\n\r\n return difference === 0;\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * The COSE algorithm registry [IANA, \"COSE Algorithms\"].\r\n *\r\n * The registry has two generations of ECDSA entries and the difference is the\r\n * point of RFC 9864. `ES256` names a digest and leaves the curve to the key,\r\n * so one identifier covers several curves and a verifier learns which one only\r\n * from the key it was handed; the fully-specified `ESP256` names both. The\r\n * older three are kept here — they are what nearly every deployed message\r\n * carries — and are marked deprecated.\r\n *\r\n * `ESB320` pairs a 320-bit curve with SHA-384, which looks like a typo and is\r\n * not: it is what RFC 9864 registers.\r\n */\r\n\r\nimport { CoseError } from './errors.ts';\r\nimport { cbor } from './cbor.ts';\r\nimport type { CborValue } from './cbor.ts';\r\nimport { CoseCurves } from './curve.ts';\r\nimport type { CoseCurve } from './curve.ts';\r\nimport { digest, sign, verify } from './ecdsa.ts';\r\nimport type { DigestAlgorithm } from './ecdsa.ts';\r\nimport { eddsaSign, eddsaVerify } from './eddsa.ts';\r\nimport { mldsaSign, mldsaVerify } from './mldsa.ts';\r\nimport { macTag, tagsEqual } from './hmac.ts';\r\n\r\n\r\n/**\r\n * Which machinery an algorithm needs.\r\n *\r\n * The distinction that earns its place here is `ecdsa` against the other two:\r\n * ECDSA signs a *digest* of the message, chosen by the algorithm, while EdDSA\r\n * and ML-DSA are pure and take the message itself. Handing a pure signer a\r\n * digest produces a signature that is valid for the digest and that nobody\r\n * else will ever accept — a failure with no symptom until the day two\r\n * implementations meet.\r\n */\r\nexport type AlgorithmFamily = 'ecdsa' | 'eddsa' | 'mldsa' | 'hmac'\r\n | 'aesgcm' | 'keywrap' | 'direct' | 'none';\r\n\r\n\r\n/** An algorithm in the COSE registry. */\r\nexport interface CoseAlgorithm {\r\n\r\n /** The IANA identifier, as it travels in the `alg` header parameter. */\r\n readonly id: number;\r\n\r\n /** The registered name, e.g. `ES256`. Case sensitive. */\r\n readonly name: string;\r\n\r\n /** The registered description. */\r\n readonly description: string;\r\n\r\n /** Which signature machinery this needs. */\r\n readonly family: AlgorithmFamily;\r\n\r\n /** The message digest, or null for a pure scheme that defines none. */\r\n readonly hash: DigestAlgorithm | null;\r\n\r\n /** The curve this algorithm is defined on, or null when it leaves it to the key. */\r\n readonly curve: CoseCurve | null;\r\n\r\n /** The ML-DSA parameter set, or null for everything else. */\r\n readonly parameterSet: string | null;\r\n\r\n /**\r\n * The width of the authentication tag in bytes, for a MAC algorithm.\r\n *\r\n * It is part of the identifier rather than a parameter: `HMAC 256/64` and\r\n * `HMAC 256/256` are two registered algorithms over the same hash, and a\r\n * verifier learns which width to expect from the message.\r\n */\r\n readonly tagSize: number | null;\r\n\r\n /**\r\n * The width of the key in bytes, for an algorithm that fixes one.\r\n *\r\n * AES algorithms do: `A128GCM` and `A256GCM` are two registered identifiers\r\n * over one cipher, and the width is what tells them apart. The signature\r\n * algorithms leave it to the curve or to the parameter set.\r\n */\r\n readonly keySize: number | null;\r\n\r\n /** Whether this implementation can sign and verify with it. */\r\n readonly signing: boolean;\r\n\r\n /** Whether the registry marks it deprecated. */\r\n readonly deprecated: boolean;\r\n\r\n}\r\n\r\n\r\ninterface AlgorithmSpec {\r\n readonly family?: AlgorithmFamily;\r\n readonly hash?: DigestAlgorithm;\r\n readonly curve?: CoseCurve;\r\n readonly parameterSet?: string;\r\n readonly tagSize?: number;\r\n readonly keySize?: number;\r\n readonly signing?: boolean;\r\n readonly deprecated?: boolean;\r\n}\r\n\r\nconst algorithm = (id: number, name: string, description: string,\r\n spec: AlgorithmSpec = {}): CoseAlgorithm => ({\r\n id,\r\n name,\r\n description,\r\n family: spec.family ?? 'none',\r\n hash: spec.hash ?? null,\r\n curve: spec.curve ?? null,\r\n parameterSet: spec.parameterSet ?? null,\r\n tagSize: spec.tagSize ?? null,\r\n keySize: spec.keySize ?? null,\r\n signing: spec.signing ?? false,\r\n deprecated: spec.deprecated ?? false,\r\n});\r\n\r\n\r\n/** The algorithms this implementation knows by name. */\r\nexport const CoseAlgorithms = {\r\n\r\n // ECDSA, curve taken from the key [RFC 9053]. Deprecated by RFC 9864.\r\n ES256: algorithm( -7, 'ES256', 'ECDSA w/ SHA-256',\r\n { family: 'ecdsa', hash: 'sha256', signing: true, deprecated: true }),\r\n ES384: algorithm( -35, 'ES384', 'ECDSA w/ SHA-384',\r\n { family: 'ecdsa', hash: 'sha384', signing: true, deprecated: true }),\r\n ES512: algorithm( -36, 'ES512', 'ECDSA w/ SHA-512',\r\n { family: 'ecdsa', hash: 'sha512', signing: true, deprecated: true }),\r\n\r\n ES256K: algorithm( -47, 'ES256K', 'ECDSA using secp256k1 curve and SHA-256',\r\n { family: 'ecdsa', hash: 'sha256', curve: CoseCurves.secp256k1, signing: true }),\r\n\r\n // Fully-specified ECDSA [RFC 9864].\r\n ESP256: algorithm( -9, 'ESP256', 'ECDSA using P-256 curve and SHA-256',\r\n { family: 'ecdsa', hash: 'sha256', curve: CoseCurves.P256, signing: true }),\r\n ESP384: algorithm( -51, 'ESP384', 'ECDSA using P-384 curve and SHA-384',\r\n { family: 'ecdsa', hash: 'sha384', curve: CoseCurves.P384, signing: true }),\r\n ESP512: algorithm( -52, 'ESP512', 'ECDSA using P-521 curve and SHA-512',\r\n { family: 'ecdsa', hash: 'sha512', curve: CoseCurves.P521, signing: true }),\r\n\r\n ESB256: algorithm(-265, 'ESB256', 'ECDSA using BrainpoolP256r1 curve and SHA-256',\r\n { family: 'ecdsa', hash: 'sha256', curve: CoseCurves.brainpoolP256r1, signing: true }),\r\n ESB320: algorithm(-266, 'ESB320', 'ECDSA using BrainpoolP320r1 curve and SHA-384',\r\n { family: 'ecdsa', hash: 'sha384', curve: CoseCurves.brainpoolP320r1, signing: true }),\r\n ESB384: algorithm(-267, 'ESB384', 'ECDSA using BrainpoolP384r1 curve and SHA-384',\r\n { family: 'ecdsa', hash: 'sha384', curve: CoseCurves.brainpoolP384r1, signing: true }),\r\n ESB512: algorithm(-268, 'ESB512', 'ECDSA using BrainpoolP512r1 curve and SHA-512',\r\n { family: 'ecdsa', hash: 'sha512', curve: CoseCurves.brainpoolP512r1, signing: true }),\r\n\r\n // EdDSA [RFC 8032]. No digest of its own: the message is signed whole.\r\n // The un-suffixed identifier leaves the curve to the key, which is what\r\n // RFC 9864 deprecates it for.\r\n EdDSA: algorithm( -8, 'EdDSA', 'EdDSA',\r\n { family: 'eddsa', signing: true, deprecated: true }),\r\n Ed25519: algorithm( -19, 'Ed25519', 'EdDSA using the Ed25519 parameter set',\r\n { family: 'eddsa', curve: CoseCurves.Ed25519, signing: true }),\r\n Ed448: algorithm( -53, 'Ed448', 'EdDSA using the Ed448 parameter set',\r\n { family: 'eddsa', curve: CoseCurves.Ed448, signing: true }),\r\n\r\n // ML-DSA [FIPS 204, RFC 9964]. Also pure, and also without a curve: an\r\n // ML-DSA key is a key pair of an algorithm rather than a point on\r\n // something, which is why RFC 9964 gives it a key type of its own.\r\n MLDSA44: algorithm( -48, 'ML-DSA-44', 'CBOR Object Signing Algorithm for ML-DSA-44',\r\n { family: 'mldsa', parameterSet: 'ML-DSA-44', signing: true }),\r\n MLDSA65: algorithm( -49, 'ML-DSA-65', 'CBOR Object Signing Algorithm for ML-DSA-65',\r\n { family: 'mldsa', parameterSet: 'ML-DSA-65', signing: true }),\r\n MLDSA87: algorithm( -50, 'ML-DSA-87', 'CBOR Object Signing Algorithm for ML-DSA-87',\r\n { family: 'mldsa', parameterSet: 'ML-DSA-87', signing: true }),\r\n\r\n // HMAC [RFC 9053, Section 3.1]. A message authentication code rather than\r\n // a signature: symmetric, so whoever verifies one can produce one, and\r\n // `signing` is therefore false for all four. The name is \"hash size /\r\n // tag size\", and the tag is the leftmost bits of the full HMAC.\r\n HMAC256_64: algorithm( 4, 'HMAC 256/64', 'HMAC w/ SHA-256 truncated to 64 bits',\r\n { family: 'hmac', hash: 'sha256', tagSize: 8 }),\r\n HMAC256_256: algorithm( 5, 'HMAC 256/256', 'HMAC w/ SHA-256',\r\n { family: 'hmac', hash: 'sha256', tagSize: 32 }),\r\n HMAC384_384: algorithm( 6, 'HMAC 384/384', 'HMAC w/ SHA-384',\r\n { family: 'hmac', hash: 'sha384', tagSize: 48 }),\r\n HMAC512_512: algorithm( 7, 'HMAC 512/512', 'HMAC w/ SHA-512',\r\n { family: 'hmac', hash: 'sha512', tagSize: 64 }),\r\n\r\n // AES-GCM [RFC 9053, Section 4.1], the content encryption algorithms.\r\n // COSE fixes the nonce at 96 bits and the authentication tag at 128, so the\r\n // key width is the only thing left for the identifier to name.\r\n A128GCM: algorithm( 1, 'A128GCM', 'AES-GCM mode w/ 128-bit key, 128-bit tag',\r\n { family: 'aesgcm', keySize: 16, tagSize: 16 }),\r\n A192GCM: algorithm( 2, 'A192GCM', 'AES-GCM mode w/ 192-bit key, 128-bit tag',\r\n { family: 'aesgcm', keySize: 24, tagSize: 16 }),\r\n A256GCM: algorithm( 3, 'A256GCM', 'AES-GCM mode w/ 256-bit key, 128-bit tag',\r\n { family: 'aesgcm', keySize: 32, tagSize: 16 }),\r\n\r\n // AES key wrap [RFC 9053, Section 6.2.1, RFC 3394]. A recipient algorithm:\r\n // it carries a content key rather than content, and the width named here is\r\n // that of the KEY-ENCRYPTION key, not of the key being wrapped.\r\n A128KW: algorithm( -3, 'A128KW', 'AES Key Wrap w/ 128-bit key',\r\n { family: 'keywrap', keySize: 16 }),\r\n A192KW: algorithm( -4, 'A192KW', 'AES Key Wrap w/ 192-bit key',\r\n { family: 'keywrap', keySize: 24 }),\r\n A256KW: algorithm( -5, 'A256KW', 'AES Key Wrap w/ 256-bit key',\r\n { family: 'keywrap', keySize: 32 }),\r\n\r\n // The recipient algorithm that transports nothing [RFC 9053, Section\r\n // 6.1.1]: the recipient's key IS the content key. Its protected bucket and\r\n // its ciphertext must both be empty, which is what makes a COSE_Mac with\r\n // one direct recipient a COSE_Mac0 with extra ceremony.\r\n direct: algorithm( -6, 'direct', 'Direct use of content encryption key (CEK)',\r\n { family: 'direct' }),\r\n\r\n // Digests, which are algorithms in the same registry but never sign.\r\n SHA256: algorithm( -16, 'SHA-256', 'SHA-2 256-bit Hash', { hash: 'sha256' }),\r\n SHA384: algorithm( -43, 'SHA-384', 'SHA-2 384-bit Hash', { hash: 'sha384' }),\r\n SHA512: algorithm( -44, 'SHA-512', 'SHA-2 512-bit Hash', { hash: 'sha512' }),\r\n SHA1: algorithm( -14, 'SHA-1', 'SHA-1 Hash', { deprecated: true }),\r\n\r\n} as const;\r\n\r\n\r\n/** Every registered algorithm, in registry order. */\r\nexport const ALL_ALGORITHMS: readonly CoseAlgorithm[] = Object.values(CoseAlgorithms);\r\n\r\n\r\n/** The algorithm with the given identifier, or null when it is not registered. */\r\nexport function algorithmById(id: number): CoseAlgorithm | null {\r\n return ALL_ALGORITHMS.find(each => each.id === id) ?? null;\r\n}\r\n\r\n\r\n/** The algorithm with the given name, or null. Case sensitive. */\r\nexport function algorithmByName(name: string): CoseAlgorithm | null {\r\n return ALL_ALGORITHMS.find(each => each.name === name) ?? null;\r\n}\r\n\r\n\r\n/**\r\n * The algorithm a header parameter names.\r\n *\r\n * An unregistered identifier is not an error here. A message that names an\r\n * algorithm nobody knows is still worth reading — its headers, its key\r\n * identifier and its payload are all inspectable — and it fails at the point\r\n * where it would have to be verified, where the failure means something.\r\n */\r\nexport function algorithmFromCbor(value: CborValue): CoseAlgorithm {\r\n\r\n if (value.type !== 'int')\r\n throw new CoseError('The COSE algorithm identifier must be an integer!');\r\n\r\n const id = Number(value.value);\r\n\r\n return algorithmById(id)\r\n ?? algorithm(id, `unregistered(${String(id)})`, 'An algorithm this implementation does not know');\r\n\r\n}\r\n\r\n\r\n/** The header parameter value naming this algorithm. */\r\nexport const algorithmToCbor = (value: CoseAlgorithm): CborValue =>\r\n cbor.int(value.id);\r\n\r\n\r\n/** Whether two algorithms are the same algorithm. */\r\nexport const sameAlgorithm = (left: CoseAlgorithm, right: CoseAlgorithm): boolean =>\r\n left.id === right.id;\r\n\r\n\r\n/**\r\n * The curve a signature with this algorithm runs on.\r\n *\r\n * A fully-specified algorithm names it, and then the key has to agree; the\r\n * three older ones leave it to the key entirely. Checking the agreement is\r\n * what stops a `ESP256` message from being verified with a P-384 key, which no\r\n * amount of correct arithmetic further down would catch.\r\n */\r\nexport function resolveCurve(value: CoseAlgorithm, keyCurve: CoseCurve | null): CoseCurve {\r\n\r\n if (!value.signing)\r\n throw new CoseError(`The COSE algorithm '${value.name}' is not a signature algorithm this implementation supports!`);\r\n\r\n if (value.curve !== null) {\r\n\r\n if (keyCurve !== null && keyCurve.id !== value.curve.id)\r\n throw new CoseError(`The COSE algorithm '${value.name}' is defined on the curve '${value.curve.name}', but the key is on the curve '${keyCurve.name}'!`);\r\n\r\n return value.curve;\r\n\r\n }\r\n\r\n if (keyCurve === null)\r\n throw new CoseError(`The COSE algorithm '${value.name}' does not name a curve, therefore the key has to!`);\r\n\r\n return keyCurve;\r\n\r\n}\r\n\r\n\r\nfunction hashOf(value: CoseAlgorithm): DigestAlgorithm {\r\n\r\n if (value.hash === null)\r\n throw new CoseError(`The COSE algorithm '${value.name}' does not define a separate message digest!`);\r\n\r\n return value.hash;\r\n\r\n}\r\n\r\n\r\nfunction parameterSetOf(value: CoseAlgorithm): string {\r\n\r\n if (value.parameterSet === null)\r\n throw new CoseError(`The COSE algorithm '${value.name}' does not name an ML-DSA parameter set!`);\r\n\r\n return value.parameterSet;\r\n\r\n}\r\n\r\n\r\n/**\r\n * Sign the Sig_structure of a message with the given algorithm.\r\n *\r\n * Note which of the three branches hashes and which do not. ECDSA signs a\r\n * digest of the Sig_structure; EdDSA and ML-DSA sign the Sig_structure itself.\r\n * Getting that backwards yields a signature that verifies against nothing but\r\n * an implementation making the same mistake.\r\n */\r\nexport function signWith(value: CoseAlgorithm,\r\n keyCurve: CoseCurve | null,\r\n toBeSigned: Uint8Array,\r\n privateKey: Uint8Array): Uint8Array {\r\n\r\n switch (value.family) {\r\n\r\n case 'ecdsa':\r\n return sign(resolveCurve(value, keyCurve),\r\n digest(hashOf(value), toBeSigned),\r\n privateKey);\r\n\r\n case 'eddsa':\r\n return eddsaSign(resolveCurve(value, keyCurve), toBeSigned, privateKey);\r\n\r\n case 'mldsa':\r\n return mldsaSign(parameterSetOf(value), toBeSigned, privateKey);\r\n\r\n default:\r\n throw new CoseError(`The COSE algorithm '${value.name}' is not a signature algorithm this implementation supports!`);\r\n\r\n }\r\n\r\n}\r\n\r\n\r\n/**\r\n * The authentication tag of a MAC_structure.\r\n *\r\n * Deliberately *not* reachable through {@link signWith}: a MAC is not a\r\n * signature with a shorter key, and an API that let one stand in for the other\r\n * would let a caller believe a message was signed when it was merely\r\n * authenticated between two parties who share a secret.\r\n */\r\nexport function macWith(value: CoseAlgorithm,\r\n toBeMaced: Uint8Array,\r\n key: Uint8Array): Uint8Array {\r\n\r\n if (value.family !== 'hmac')\r\n throw new CoseError(`The COSE algorithm '${value.name}' is not a message authentication algorithm this implementation supports!`);\r\n\r\n return macTag(hashOf(value), tagSizeOf(value), key, toBeMaced);\r\n\r\n}\r\n\r\n\r\n/** Whether an authentication tag is the right one, compared in constant time. */\r\nexport function verifyMacWith(value: CoseAlgorithm,\r\n toBeMaced: Uint8Array,\r\n tag: Uint8Array,\r\n key: Uint8Array): boolean {\r\n\r\n return tagsEqual(macWith(value, toBeMaced, key), tag);\r\n\r\n}\r\n\r\n\r\nfunction tagSizeOf(value: CoseAlgorithm): number {\r\n\r\n if (value.tagSize === null)\r\n throw new CoseError(`The COSE algorithm '${value.name}' does not define an authentication tag width!`);\r\n\r\n return value.tagSize;\r\n\r\n}\r\n\r\n\r\n/** Verify a signature over the Sig_structure of a message. */\r\nexport function verifyWith(value: CoseAlgorithm,\r\n keyCurve: CoseCurve | null,\r\n toBeSigned: Uint8Array,\r\n signature: Uint8Array,\r\n publicKey: Uint8Array): boolean {\r\n\r\n switch (value.family) {\r\n\r\n case 'ecdsa':\r\n return verify(resolveCurve(value, keyCurve),\r\n signature,\r\n digest(hashOf(value), toBeSigned),\r\n publicKey);\r\n\r\n case 'eddsa':\r\n return eddsaVerify(resolveCurve(value, keyCurve), signature, toBeSigned, publicKey);\r\n\r\n case 'mldsa':\r\n return mldsaVerify(parameterSetOf(value), signature, toBeSigned, publicKey);\r\n\r\n default:\r\n throw new CoseError(`The COSE algorithm '${value.name}' is not a signature algorithm this implementation supports!`);\r\n\r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * A bucket of COSE header parameters [RFC 9052, Section 3].\r\n *\r\n * A signed COSE message carries two of them. The protected bucket is covered\r\n * by the signature; the unprotected bucket is not, and therefore must not be\r\n * trusted after a successful verification — the key identifier of nearly every\r\n * deployed message lives there, and so does anything an attacker on the path\r\n * would like to change.\r\n *\r\n * Buckets are immutable, because the serialization of a protected bucket is\r\n * part of a signature input and must not change after signing. `set` returns a\r\n * copy: an unprotected bucket does need to change after signing, since a\r\n * countersignature is added to a message that is already finished.\r\n */\r\n\r\nimport { algorithmFromCbor, algorithmToCbor } from './algorithm.ts';\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport { cbor, decode, encode, NO_BYTES } from './cbor.ts';\r\nimport type { CborEntry, CborValue } from './cbor.ts';\r\nimport { CoseError, notVerified, VERIFIED } from './errors.ts';\r\nimport type { Verification } from './errors.ts';\r\nimport { HeaderLabel, headerLabelName,\r\n isUnderstood, label, sameLabel } from './labels.ts';\r\n\r\n\r\nexport class CoseHeaders {\r\n\r\n /** The header parameters, in the order they were given or read. */\r\n public readonly parameters: readonly CborEntry[];\r\n\r\n\r\n public constructor(parameters: readonly CborEntry[] = []) {\r\n\r\n this.parameters = [...parameters];\r\n\r\n for (let index = 0; index < this.parameters.length; index++) {\r\n for (let other = 0; other < index; other++) {\r\n if (sameLabel(this.parameters[index]![0], this.parameters[other]![0]))\r\n throw new CoseError(`The COSE header parameter '${headerLabelName(this.parameters[index]![0])}' was given more than once!`);\r\n }\r\n }\r\n\r\n }\r\n\r\n\r\n /**\r\n * A bucket without any header parameters. As a protected bucket it is\r\n * serialized as a zero-length byte string.\r\n */\r\n public static readonly empty = new CoseHeaders();\r\n\r\n\r\n /** How many header parameters this bucket holds. */\r\n public get count(): number {\r\n return this.parameters.length;\r\n }\r\n\r\n /** Whether this bucket has no header parameters at all. */\r\n public get isEmpty(): boolean {\r\n return this.parameters.length === 0;\r\n }\r\n\r\n\r\n /**\r\n * The bucket holding the two header parameters almost every signed COSE\r\n * message uses.\r\n */\r\n public static create(algorithm?: CoseAlgorithm | null,\r\n keyIdentifier?: Uint8Array | null): CoseHeaders {\r\n\r\n const parameters: CborEntry[] = [];\r\n\r\n if (algorithm !== undefined && algorithm !== null)\r\n parameters.push([label(HeaderLabel.algorithm), algorithmToCbor(algorithm)]);\r\n\r\n if (keyIdentifier !== undefined && keyIdentifier !== null)\r\n parameters.push([label(HeaderLabel.keyIdentifier), cbor.bytes(keyIdentifier)]);\r\n\r\n return new CoseHeaders(parameters);\r\n\r\n }\r\n\r\n\r\n /** Parse the given CBOR map as a bucket of header parameters. */\r\n public static parse(value: CborValue): CoseHeaders {\r\n\r\n if (value.type !== 'map')\r\n throw new CoseError(`A bucket of COSE header parameters must be a CBOR map, but was a CBOR ${value.type}!`);\r\n\r\n return new CoseHeaders(value.entries);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Parse the serialized protected bucket of a COSE message.\r\n *\r\n * A zero-length byte string is an empty bucket and *not* an encoded empty\r\n * map. It is the one encoding that must never be \"repaired\" into `A0`,\r\n * because the signature covers these exact bytes [RFC 9052, Section 3].\r\n *\r\n * This is deliberately a separate function rather than an overload: a byte\r\n * array is also a perfectly good CBOR byte string, and the two readings of\r\n * the same argument mean very different things here.\r\n */\r\n public static parseProtected(protectedBytes: Uint8Array): CoseHeaders {\r\n\r\n if (protectedBytes.length === 0)\r\n return CoseHeaders.empty;\r\n\r\n return CoseHeaders.parse(decode(protectedBytes));\r\n\r\n }\r\n\r\n\r\n /** The value of the given header parameter, or null. */\r\n public get(labelValue: CborValue): CborValue | null {\r\n\r\n for (const [key, value] of this.parameters) {\r\n if (sameLabel(key, labelValue))\r\n return value;\r\n }\r\n\r\n return null;\r\n\r\n }\r\n\r\n /** Whether the given header parameter is present within this bucket. */\r\n public has(labelValue: CborValue): boolean {\r\n return this.get(labelValue) !== null;\r\n }\r\n\r\n\r\n /**\r\n * Return a copy in which the given header parameter is set, replacing it\r\n * in place when it is already present and appending it otherwise.\r\n */\r\n public set(labelValue: CborValue, value: CborValue): CoseHeaders {\r\n\r\n const updated: CborEntry[] = [];\r\n let replaced = false;\r\n\r\n for (const entry of this.parameters) {\r\n\r\n if (sameLabel(entry[0], labelValue)) {\r\n updated.push([labelValue, value]);\r\n replaced = true;\r\n }\r\n else\r\n updated.push(entry);\r\n\r\n }\r\n\r\n if (!replaced)\r\n updated.push([labelValue, value]);\r\n\r\n return new CoseHeaders(updated);\r\n\r\n }\r\n\r\n\r\n /** The cryptographic algorithm (label 1), or null when absent. */\r\n public get algorithm(): CoseAlgorithm | null {\r\n\r\n const value = this.get(label(HeaderLabel.algorithm));\r\n\r\n if (value?.type !== 'int')\r\n return null;\r\n\r\n return algorithmFromCbor(value);\r\n\r\n }\r\n\r\n /** The key identifier (label 4), or null when absent or not a byte string. */\r\n public get keyIdentifier(): Uint8Array | null {\r\n\r\n const value = this.get(label(HeaderLabel.keyIdentifier));\r\n\r\n return value !== null && value.type === 'bytes' ? value.value : null;\r\n\r\n }\r\n\r\n /** The content type (label 3), or null when absent. */\r\n public get contentType(): CborValue | null {\r\n return this.get(label(HeaderLabel.contentType));\r\n }\r\n\r\n /** The labels a recipient is required to understand (label 2), or null. */\r\n public get critical(): readonly CborValue[] | null {\r\n\r\n const value = this.get(label(HeaderLabel.critical));\r\n\r\n return value !== null && value.type === 'array' ? value.items : null;\r\n\r\n }\r\n\r\n\r\n /** A CBOR map holding these header parameters, in their own order. */\r\n public toCbor(): CborValue {\r\n return cbor.map(this.parameters);\r\n }\r\n\r\n\r\n /**\r\n * The serialization of this bucket for use as the PROTECTED bucket of a\r\n * COSE message: a zero-length byte string when the bucket is empty, and\r\n * the encoded map otherwise [RFC 9052, Section 3].\r\n *\r\n * These are the exact bytes a signature is computed over, so they have to\r\n * be transmitted and stored verbatim.\r\n */\r\n public toProtectedBytes(): Uint8Array {\r\n return this.isEmpty ? NO_BYTES : encode(this.toCbor());\r\n }\r\n\r\n}\r\n\r\n\r\n/**\r\n * Check the `crit` header parameter of a pair of buckets\r\n * [RFC 9052, Section 3.1].\r\n *\r\n * Every label listed there has to be present within the protected bucket and\r\n * has to be understood and processed by whoever is verifying, otherwise the\r\n * whole message is rejected. `alsoUnderstood` is how a caller that genuinely\r\n * processes a parameter says so — validating a certificate chain, for\r\n * instance — because what counts as understood is a property of the\r\n * verification being performed rather than of this library.\r\n */\r\nexport function verifyCriticalHeaderParameters(protectedHeader: CoseHeaders,\r\n unprotectedHeader: CoseHeaders,\r\n alsoUnderstood: readonly CborValue[] = []): Verification {\r\n\r\n if (unprotectedHeader.has(label(HeaderLabel.critical)))\r\n return notVerified('The \"crit\" header parameter must be placed within the protected header bucket!');\r\n\r\n const critical = protectedHeader.critical;\r\n\r\n if (critical === null) {\r\n\r\n if (protectedHeader.has(label(HeaderLabel.critical)))\r\n return notVerified('The \"crit\" header parameter must be an array of header parameter labels!');\r\n\r\n return VERIFIED;\r\n\r\n }\r\n\r\n if (critical.length === 0)\r\n return notVerified('The \"crit\" header parameter must list at least one header parameter label!');\r\n\r\n for (const each of critical) {\r\n\r\n if (!protectedHeader.has(each))\r\n return notVerified(`The \"crit\" header parameter lists '${headerLabelName(each)}', which is not present within the protected header bucket!`);\r\n\r\n if (!isUnderstood(each) && !alsoUnderstood.some(other => sameLabel(other, each)))\r\n return notVerified(`The \"crit\" header parameter demands that '${headerLabelName(each)}' be understood, which this implementation does not!`);\r\n\r\n }\r\n\r\n return VERIFIED;\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * A COSE key: elliptic curve (EC2), octet key pair (OKP) or algorithm key\r\n * pair (AKP) [RFC 9052 Section 7, RFC 9964].\r\n *\r\n * **The labels are not the same for all three.** On an EC2 or OKP key, −1 is\r\n * the curve and −2 is the x coordinate; on an AKP key, −1 is the public key\r\n * and −2 is the private one. A parser that switches on the label alone reads\r\n * an ML-DSA public key as a curve identifier and says nothing. Everything here\r\n * therefore establishes the key type first and interprets the rest in its\r\n * light.\r\n *\r\n * On EC2 and OKP keys, coordinates and private keys are fixed-width byte\r\n * strings whose **leading zeroes must be preserved** [RFC 9053, Section\r\n * 7.1.1]. A plain big-integer serialization shortens them roughly one time in\r\n * 256, and the resulting key is rejected by other implementations — a bug that\r\n * passes every test until the day it does not. Every width is therefore\r\n * checked on the way out of this module, and every value is padded on the way\r\n * in.\r\n */\r\n\r\nimport { algorithmFromCbor, algorithmToCbor } from './algorithm.ts';\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport { cbor, decode, DETERMINISTIC,\r\n encode } from './cbor.ts';\r\nimport type { CborEntry, CborValue } from './cbor.ts';\r\nimport { curveById, KEY_TYPE_EC2,\r\n KEY_TYPE_OKP } from './curve.ts';\r\nimport type { CoseCurve } from './curve.ts';\r\nimport { decompressY, digest, isOnCurve,\r\n publicKeyFor } from './ecdsa.ts';\r\nimport type { DigestAlgorithm } from './ecdsa.ts';\r\nimport { eddsaPublicKeyFor } from './eddsa.ts';\r\nimport { CoseError } from './errors.ts';\r\nimport { MLDSA_SEED_SIZE, MLDSA_SIZES,\r\n mldsaPublicKeyFor } from './mldsa.ts';\r\nimport type { MldsaParameterSet } from './mldsa.ts';\r\n\r\n\r\n/** Key type 7, a key pair belonging to an algorithm rather than a curve. */\r\nexport const KEY_TYPE_AKP = 7;\r\n\r\n/** Key type 4, a shared secret [RFC 9053, Section 7.3]. */\r\nexport const KEY_TYPE_SYMMETRIC = 4;\r\n\r\n\r\n/**\r\n * The labels of a COSE *key*, which are not the labels of a header bucket:\r\n * 3 is the algorithm here and the content type there, 4 is the key operations\r\n * here and the key identifier there.\r\n */\r\nexport const KeyLabel = {\r\n keyType: 1,\r\n keyIdentifier: 2,\r\n algorithm: 3,\r\n keyOperations: 4,\r\n\r\n // EC2 and OKP.\r\n curve: -1,\r\n x: -2,\r\n y: -3,\r\n d: -4,\r\n\r\n // AKP [RFC 9964] — note the collision with the two above.\r\n pub: -1,\r\n priv: -2,\r\n\r\n // Symmetric [RFC 9053, Section 7.3] — and that is label −1 meaning a\r\n // third thing: the curve on an EC2 or OKP key, the public key on an AKP\r\n // one, and here the shared secret itself.\r\n k: -1,\r\n} as const;\r\n\r\n\r\n/** Zero-pad a big-endian value to the given width, or refuse to shorten it. */\r\nfunction padded(value: Uint8Array, width: number, what: string): Uint8Array {\r\n\r\n if (value.length === width)\r\n return value;\r\n\r\n if (value.length > width) {\r\n\r\n // Leading zeroes may be dropped; significant bytes may not.\r\n const excess = value.length - width;\r\n\r\n for (let index = 0; index < excess; index++) {\r\n if (value[index] !== 0)\r\n throw new CoseError(`The ${what} of a COSE key must be ${String(width)} bytes wide, but a ${String(value.length)}-byte value was given that does not fit!`);\r\n }\r\n\r\n return value.slice(excess);\r\n\r\n }\r\n\r\n const result = new Uint8Array(width);\r\n result.set(value, width - value.length);\r\n\r\n return result;\r\n\r\n}\r\n\r\n\r\nexport interface CoseKeyParts {\r\n readonly keyIdentifier?: Uint8Array | null;\r\n readonly algorithm?: CoseAlgorithm | null;\r\n}\r\n\r\n\r\ninterface CoseKeyFields {\r\n keyType: number;\r\n keyIdentifier: Uint8Array | null;\r\n algorithm: CoseAlgorithm | null;\r\n keyOperations: CborValue | null;\r\n curveId: number | null;\r\n x: Uint8Array | null;\r\n y: Uint8Array | null;\r\n d: Uint8Array | null;\r\n pub: Uint8Array | null;\r\n priv: Uint8Array | null;\r\n k: Uint8Array | null;\r\n additional: readonly CborEntry[];\r\n}\r\n\r\n\r\nexport class CoseKey {\r\n\r\n public readonly keyType: number;\r\n public readonly keyIdentifier: Uint8Array | null;\r\n public readonly algorithm: CoseAlgorithm | null;\r\n public readonly keyOperations: CborValue | null;\r\n\r\n /** The curve identifier as it travels, also when it is not registered. */\r\n public readonly curveId: number | null;\r\n\r\n /** EC2 and OKP: the coordinates and the private scalar. */\r\n public readonly x: Uint8Array | null;\r\n public readonly y: Uint8Array | null;\r\n public readonly d: Uint8Array | null;\r\n\r\n /** AKP: the public key, and the private key — which is always the seed. */\r\n public readonly pub: Uint8Array | null;\r\n public readonly priv: Uint8Array | null;\r\n\r\n /** Symmetric: the shared secret. There is no public half of one. */\r\n public readonly k: Uint8Array | null;\r\n\r\n /** Header parameters this implementation does not know, kept for the round trip. */\r\n public readonly additional: readonly CborEntry[];\r\n\r\n\r\n private constructor(fields: CoseKeyFields) {\r\n this.keyType = fields.keyType;\r\n this.keyIdentifier = fields.keyIdentifier;\r\n this.algorithm = fields.algorithm;\r\n this.keyOperations = fields.keyOperations;\r\n this.curveId = fields.curveId;\r\n this.x = fields.x;\r\n this.y = fields.y;\r\n this.d = fields.d;\r\n this.pub = fields.pub;\r\n this.priv = fields.priv;\r\n this.k = fields.k;\r\n this.additional = fields.additional;\r\n }\r\n\r\n\r\n private get fields(): CoseKeyFields {\r\n return {\r\n keyType: this.keyType,\r\n keyIdentifier: this.keyIdentifier,\r\n algorithm: this.algorithm,\r\n keyOperations: this.keyOperations,\r\n curveId: this.curveId,\r\n x: this.x,\r\n y: this.y,\r\n d: this.d,\r\n pub: this.pub,\r\n priv: this.priv,\r\n k: this.k,\r\n additional: this.additional,\r\n };\r\n }\r\n\r\n private copy(overrides: Partial<CoseKeyFields>): CoseKey {\r\n return new CoseKey({ ...this.fields, ...overrides });\r\n }\r\n\r\n\r\n /** The curve of this key, or null when it names none or an unregistered one. */\r\n public get curve(): CoseCurve | null {\r\n return this.curveId === null ? null : curveById(this.curveId);\r\n }\r\n\r\n /**\r\n * Whether this key carries secret key material.\r\n *\r\n * A symmetric key is *always* secret — it has nothing else — which is why\r\n * `k` counts here beside the two private halves.\r\n */\r\n public get isPrivate(): boolean {\r\n return this.d !== null || this.priv !== null || this.k !== null;\r\n }\r\n\r\n\r\n /**\r\n * An elliptic curve key pair from its private scalar.\r\n *\r\n * The public point is recomputed rather than asked for, which is what the\r\n * examples of RFC 9052 do as well: a private COSE key always carries the\r\n * full pair, and the two halves cannot disagree.\r\n */\r\n public static fromPrivateScalar(curve: CoseCurve,\r\n d: Uint8Array,\r\n parts: CoseKeyParts = {}): CoseKey {\r\n\r\n if (curve.keyType === KEY_TYPE_OKP)\r\n return CoseKey.fromOkpPrivateKey(curve, d, parts);\r\n\r\n const scalar = padded(d, curve.orderSize ?? d.length, 'private key');\r\n const uncompressed = publicKeyFor(curve, scalar);\r\n const fieldSize = curve.fieldSize ?? 0;\r\n\r\n return new CoseKey({\r\n ...empty(curve.keyType, parts),\r\n curveId: curve.id,\r\n x: uncompressed.slice(1, 1 + fieldSize),\r\n y: uncompressed.slice(1 + fieldSize),\r\n d: scalar,\r\n });\r\n\r\n }\r\n\r\n\r\n /**\r\n * An octet key pair from its private key.\r\n *\r\n * There is no `y`: an EdDSA public key is the whole of `x`.\r\n */\r\n public static fromOkpPrivateKey(curve: CoseCurve,\r\n d: Uint8Array,\r\n parts: CoseKeyParts = {}): CoseKey {\r\n\r\n const width = curve.orderSize ?? d.length;\r\n\r\n if (d.length !== width)\r\n throw new CoseError(`The private key of a COSE key on the curve '${curve.name}' must be ${String(width)} bytes long, but was ${String(d.length)} bytes long!`);\r\n\r\n return new CoseKey({\r\n ...empty(KEY_TYPE_OKP, parts),\r\n curveId: curve.id,\r\n x: eddsaPublicKeyFor(curve, d),\r\n d,\r\n });\r\n\r\n }\r\n\r\n\r\n /**\r\n * An algorithm key pair from its seed.\r\n *\r\n * The private key of an ML-DSA COSE key is the 32-byte seed and nothing\r\n * else [RFC 9964] — not the expanded secret key, which is up to 4896 bytes\r\n * and derivable from it. The algorithm is not optional here: an ML-DSA\r\n * public key does not say which parameter set produced it, so a key that\r\n * did not name one could not be used, and could not even be identified,\r\n * since its thumbprint covers the algorithm.\r\n */\r\n public static fromAkpSeed(algorithm: CoseAlgorithm,\r\n seed: Uint8Array,\r\n parts: CoseKeyParts = {}): CoseKey {\r\n\r\n if (algorithm.parameterSet === null)\r\n throw new CoseError(`The COSE algorithm '${algorithm.name}' is not an algorithm key pair algorithm!`);\r\n\r\n if (seed.length !== MLDSA_SEED_SIZE)\r\n throw new CoseError(`The private key of an algorithm key pair is the seed and must be ${String(MLDSA_SEED_SIZE)} bytes long [RFC 9964], but was ${String(seed.length)} bytes long!`);\r\n\r\n return new CoseKey({\r\n ...empty(KEY_TYPE_AKP, { ...parts, algorithm }),\r\n pub: mldsaPublicKeyFor(algorithm.parameterSet, seed),\r\n priv: seed,\r\n });\r\n\r\n }\r\n\r\n\r\n /**\r\n * A public algorithm key pair, from the public key alone.\r\n *\r\n * This is the form a certificate hands over: a `SubjectPublicKeyInfo`\r\n * carries the public key and names the parameter set in its algorithm\r\n * identifier, and there is no seed to be had. The algorithm is required\r\n * for the same reason as in {@link fromAkpSeed} — the bytes do not say\r\n * which parameter set produced them, and the thumbprint covers `alg`.\r\n */\r\n public static fromAkpPublicKey(algorithm: CoseAlgorithm,\r\n pub: Uint8Array,\r\n parts: CoseKeyParts = {}): CoseKey {\r\n\r\n if (algorithm.parameterSet === null)\r\n throw new CoseError(`The COSE algorithm '${algorithm.name}' is not an algorithm key pair algorithm!`);\r\n\r\n const expected = MLDSA_SIZES[algorithm.parameterSet as MldsaParameterSet].publicKey;\r\n\r\n if (pub.length !== expected)\r\n throw new CoseError(`The public key of an '${algorithm.name}' algorithm key pair must be ${String(expected)} bytes long, but was ${String(pub.length)} bytes long!`);\r\n\r\n return new CoseKey({\r\n ...empty(KEY_TYPE_AKP, { ...parts, algorithm }),\r\n pub,\r\n });\r\n\r\n }\r\n\r\n\r\n /**\r\n * A symmetric key, which is a shared secret and nothing else.\r\n *\r\n * No length is enforced. RFC 9053 says an HMAC key SHOULD be as wide as\r\n * the hash output, which is advice about key management rather than a rule\r\n * about the primitive — RFC 2104 accepts any width and the published test\r\n * vectors of RFC 4231 include a four-byte key. What a caller must not do\r\n * is derive one from a password, and no length check would catch that.\r\n */\r\n public static fromSymmetricKey(k: Uint8Array,\r\n parts: CoseKeyParts = {}): CoseKey {\r\n\r\n if (k.length === 0)\r\n throw new CoseError('A symmetric COSE key must carry a key value!');\r\n\r\n return new CoseKey({\r\n ...empty(KEY_TYPE_SYMMETRIC, parts),\r\n k,\r\n });\r\n\r\n }\r\n\r\n\r\n /** A public octet key pair, which is the whole of `x` and nothing else. */\r\n public static fromOkpPublicKey(curve: CoseCurve,\r\n x: Uint8Array,\r\n parts: CoseKeyParts = {}): CoseKey {\r\n\r\n return new CoseKey({\r\n ...empty(KEY_TYPE_OKP, parts),\r\n curveId: curve.id,\r\n x,\r\n });\r\n\r\n }\r\n\r\n\r\n /** A public elliptic curve key from its coordinates. */\r\n public static fromCoordinates(curve: CoseCurve,\r\n x: Uint8Array,\r\n y: Uint8Array,\r\n parts: CoseKeyParts = {}): CoseKey {\r\n\r\n const width = curve.fieldSize ?? x.length;\r\n\r\n return new CoseKey({\r\n ...empty(curve.keyType, parts),\r\n curveId: curve.id,\r\n x: padded(x, width, 'x coordinate'),\r\n y: padded(y, width, 'y coordinate'),\r\n });\r\n\r\n }\r\n\r\n\r\n /**\r\n * Parse a COSE key.\r\n *\r\n * Widths are deliberately not checked here — only that the CBOR types are\r\n * what they claim to be. A key with a shortened coordinate is a real key\r\n * that a real implementation produced, and reading it is how one finds out\r\n * that it is wrong; the refusal belongs at the point where the key would\r\n * be used, where the error can say what was expected.\r\n *\r\n * A duplicate label takes its last value, which is what a lenient CBOR map\r\n * does everywhere else in COSE.\r\n */\r\n public static parse(input: CborValue | Uint8Array): CoseKey {\r\n\r\n const value = input instanceof Uint8Array ? decode(input) : input;\r\n\r\n if (value.type !== 'map')\r\n throw new CoseError(`A COSE key must be a CBOR map, but was a CBOR ${value.type}!`);\r\n\r\n // First the key type, because it decides what −1 and −2 mean. Reading\r\n // it in a pass of its own rather than relying on it arriving first\r\n // costs one loop and survives a map in any order.\r\n const keyType = CoseKey.readKeyType(value.entries);\r\n\r\n if (keyType === KEY_TYPE_AKP)\r\n return CoseKey.parseAkp(value.entries, keyType);\r\n\r\n if (keyType === KEY_TYPE_SYMMETRIC)\r\n return CoseKey.parseSymmetric(value.entries, keyType);\r\n\r\n return CoseKey.parseCurveKey(value.entries, keyType);\r\n\r\n }\r\n\r\n\r\n private static readKeyType(entries: readonly CborEntry[]): number {\r\n\r\n for (const [key, item] of entries) {\r\n\r\n if (key.type === 'int' && Number(key.value) === KeyLabel.keyType) {\r\n\r\n if (item.type !== 'int')\r\n throw new CoseError('The key type of a COSE key must be an integer!');\r\n\r\n return Number(item.value);\r\n\r\n }\r\n\r\n }\r\n\r\n throw new CoseError('A COSE key must have a key type!');\r\n\r\n }\r\n\r\n\r\n private static parseCurveKey(entries: readonly CborEntry[], keyType: number): CoseKey {\r\n\r\n let keyIdentifier: Uint8Array | null = null;\r\n let algorithm: CoseAlgorithm | null = null;\r\n let keyOperations: CborValue | null = null;\r\n let curveId: number | null = null;\r\n let x: Uint8Array | null = null;\r\n let yValue: CborValue | null = null;\r\n let d: Uint8Array | null = null;\r\n\r\n const additional: CborEntry[] = [];\r\n\r\n for (const [key, item] of entries) {\r\n\r\n if (key.type !== 'int') {\r\n additional.push([key, item]);\r\n continue;\r\n }\r\n\r\n switch (Number(key.value)) {\r\n\r\n case KeyLabel.keyType:\r\n break;\r\n\r\n case KeyLabel.keyIdentifier:\r\n keyIdentifier = bytesOf(item, 'The key identifier of a COSE key');\r\n break;\r\n\r\n case KeyLabel.algorithm:\r\n algorithm = algorithmFromCbor(item);\r\n break;\r\n\r\n case KeyLabel.keyOperations:\r\n if (item.type !== 'array')\r\n throw new CoseError('The key operations of a COSE key must be an array!');\r\n keyOperations = item;\r\n break;\r\n\r\n case KeyLabel.curve:\r\n if (item.type !== 'int')\r\n throw new CoseError('The curve of a COSE key must be an integer!');\r\n curveId = Number(item.value);\r\n break;\r\n\r\n case KeyLabel.x:\r\n x = bytesOf(item, 'The x coordinate of a COSE key');\r\n break;\r\n\r\n case KeyLabel.y:\r\n yValue = item;\r\n break;\r\n\r\n case KeyLabel.d:\r\n d = bytesOf(item, 'The private key of a COSE key');\r\n break;\r\n\r\n default:\r\n additional.push([key, item]);\r\n\r\n }\r\n\r\n }\r\n\r\n return new CoseKey({\r\n keyType,\r\n keyIdentifier,\r\n algorithm,\r\n keyOperations,\r\n curveId,\r\n x,\r\n y: CoseKey.resolveY(yValue, x, curveId),\r\n d,\r\n pub: null,\r\n priv: null,\r\n k: null,\r\n additional,\r\n });\r\n\r\n }\r\n\r\n\r\n private static parseSymmetric(entries: readonly CborEntry[], keyType: number): CoseKey {\r\n\r\n let keyIdentifier: Uint8Array | null = null;\r\n let algorithm: CoseAlgorithm | null = null;\r\n let keyOperations: CborValue | null = null;\r\n let k: Uint8Array | null = null;\r\n\r\n const additional: CborEntry[] = [];\r\n\r\n for (const [key, item] of entries) {\r\n\r\n if (key.type !== 'int') {\r\n additional.push([key, item]);\r\n continue;\r\n }\r\n\r\n switch (Number(key.value)) {\r\n\r\n case KeyLabel.keyType:\r\n break;\r\n\r\n case KeyLabel.keyIdentifier:\r\n keyIdentifier = bytesOf(item, 'The key identifier of a COSE key');\r\n break;\r\n\r\n case KeyLabel.algorithm:\r\n algorithm = algorithmFromCbor(item);\r\n break;\r\n\r\n case KeyLabel.keyOperations:\r\n if (item.type !== 'array')\r\n throw new CoseError('The key operations of a COSE key must be an array!');\r\n keyOperations = item;\r\n break;\r\n\r\n case KeyLabel.k:\r\n k = bytesOf(item, 'The key value of a symmetric COSE key');\r\n break;\r\n\r\n default:\r\n additional.push([key, item]);\r\n break;\r\n\r\n }\r\n\r\n }\r\n\r\n // \"For symmetric keys, it is REQUIRED that 'k' be present in the\r\n // structure\" [RFC 9053, Section 7.3] — and unlike a missing public\r\n // key there is nothing to recompute it from.\r\n if (k === null)\r\n throw new CoseError('A COSE key of key type Symmetric must carry its key value [RFC 9053, Section 7.3]!');\r\n\r\n return new CoseKey({\r\n keyType,\r\n keyIdentifier,\r\n algorithm,\r\n keyOperations,\r\n curveId: null,\r\n x: null,\r\n y: null,\r\n d: null,\r\n pub: null,\r\n priv: null,\r\n k,\r\n additional,\r\n });\r\n\r\n }\r\n\r\n\r\n private static parseAkp(entries: readonly CborEntry[], keyType: number): CoseKey {\r\n\r\n let keyIdentifier: Uint8Array | null = null;\r\n let algorithm: CoseAlgorithm | null = null;\r\n let keyOperations: CborValue | null = null;\r\n let pub: Uint8Array | null = null;\r\n let priv: Uint8Array | null = null;\r\n\r\n const additional: CborEntry[] = [];\r\n\r\n for (const [key, item] of entries) {\r\n\r\n if (key.type !== 'int') {\r\n additional.push([key, item]);\r\n continue;\r\n }\r\n\r\n switch (Number(key.value)) {\r\n\r\n case KeyLabel.keyType:\r\n break;\r\n\r\n case KeyLabel.keyIdentifier:\r\n keyIdentifier = bytesOf(item, 'The key identifier of a COSE key');\r\n break;\r\n\r\n case KeyLabel.algorithm:\r\n algorithm = algorithmFromCbor(item);\r\n break;\r\n\r\n case KeyLabel.keyOperations:\r\n if (item.type !== 'array')\r\n throw new CoseError('The key operations of a COSE key must be an array!');\r\n keyOperations = item;\r\n break;\r\n\r\n case KeyLabel.pub:\r\n pub = bytesOf(item, 'The public key of an algorithm key pair');\r\n break;\r\n\r\n case KeyLabel.priv:\r\n priv = bytesOf(item, 'The private key of an algorithm key pair');\r\n break;\r\n\r\n default:\r\n additional.push([key, item]);\r\n\r\n }\r\n\r\n }\r\n\r\n return new CoseKey({\r\n keyType,\r\n keyIdentifier,\r\n algorithm,\r\n keyOperations,\r\n curveId: null,\r\n x: null,\r\n y: null,\r\n d: null,\r\n pub,\r\n priv,\r\n k: null,\r\n additional,\r\n });\r\n\r\n }\r\n\r\n\r\n /**\r\n * The y coordinate, which may travel as a byte string or as the parity bit\r\n * of a compressed point.\r\n */\r\n private static resolveY(value: CborValue | null,\r\n x: Uint8Array | null,\r\n curveId: number | null): Uint8Array | null {\r\n\r\n if (value === null)\r\n return null;\r\n\r\n if (value.type === 'bytes')\r\n return value.value;\r\n\r\n if (value.type === 'bool') {\r\n\r\n const curve = curveId === null ? null : curveById(curveId);\r\n\r\n if (curve === null)\r\n throw new CoseError('The y coordinate of a COSE key is a sign bit, which needs a known curve to be resolved!');\r\n\r\n if (x === null)\r\n throw new CoseError('The y coordinate of a COSE key is a sign bit, which needs the x coordinate to be resolved!');\r\n\r\n return decompressY(curve, x, value.value);\r\n\r\n }\r\n\r\n throw new CoseError('The y coordinate of a COSE key must be a byte string or a boolean sign bit!');\r\n\r\n }\r\n\r\n\r\n /**\r\n * A CBOR map holding this key.\r\n *\r\n * The labels are written in ascending encoded order — 1, 2, 3, 4, −1, −2,\r\n * −3, −4 — which happens to be exactly the deterministic order of\r\n * RFC 8949 Section 4.2.1, so a canonical re-encoding moves nothing.\r\n *\r\n * A key whose y arrived as a sign bit does *not* round-trip byte for byte:\r\n * y is always written as the byte string form, which every implementation\r\n * understands.\r\n */\r\n public toCbor(): CborValue {\r\n\r\n const entries: CborEntry[] = [\r\n [cbor.int(KeyLabel.keyType), cbor.int(this.keyType)],\r\n ];\r\n\r\n if (this.keyIdentifier !== null)\r\n entries.push([cbor.int(KeyLabel.keyIdentifier), cbor.bytes(this.keyIdentifier)]);\r\n\r\n if (this.algorithm !== null)\r\n entries.push([cbor.int(KeyLabel.algorithm), algorithmToCbor(this.algorithm)]);\r\n\r\n if (this.keyOperations !== null)\r\n entries.push([cbor.int(KeyLabel.keyOperations), this.keyOperations]);\r\n\r\n if (this.keyType === KEY_TYPE_AKP) {\r\n\r\n if (this.pub !== null)\r\n entries.push([cbor.int(KeyLabel.pub), cbor.bytes(this.pub)]);\r\n\r\n if (this.priv !== null)\r\n entries.push([cbor.int(KeyLabel.priv), cbor.bytes(this.priv)]);\r\n\r\n }\r\n\r\n // Encoding a symmetric key writes the secret out, always: there is no\r\n // half of it that can be published. RFC 9053 says as much — \"care must\r\n // be taken that it is never transmitted accidentally or insecurely\".\r\n else if (this.keyType === KEY_TYPE_SYMMETRIC) {\r\n\r\n if (this.k !== null)\r\n entries.push([cbor.int(KeyLabel.k), cbor.bytes(this.k)]);\r\n\r\n }\r\n\r\n else {\r\n\r\n if (this.curveId !== null)\r\n entries.push([cbor.int(KeyLabel.curve), cbor.int(this.curveId)]);\r\n\r\n if (this.x !== null)\r\n entries.push([cbor.int(KeyLabel.x), cbor.bytes(this.x)]);\r\n\r\n if (this.y !== null)\r\n entries.push([cbor.int(KeyLabel.y), cbor.bytes(this.y)]);\r\n\r\n if (this.d !== null)\r\n entries.push([cbor.int(KeyLabel.d), cbor.bytes(this.d)]);\r\n\r\n }\r\n\r\n entries.push(...this.additional);\r\n\r\n return cbor.map(entries);\r\n\r\n }\r\n\r\n\r\n /** The CBOR encoding of this key. */\r\n public toBytes(): Uint8Array {\r\n return encode(this.toCbor());\r\n }\r\n\r\n\r\n /**\r\n * This key without its private half.\r\n *\r\n * A symmetric key has no such form, and saying so is the point rather than\r\n * a limitation: RFC 9053 states outright that the structure \"does not have\r\n * a form that contains only public members\". Returning the key unchanged\r\n * here — which is what stripping `d` and `priv` from it would do — would\r\n * hand a caller the shared secret under a name promising the opposite.\r\n */\r\n public publicKey(): CoseKey {\r\n\r\n if (this.keyType === KEY_TYPE_SYMMETRIC)\r\n throw new CoseError('A COSE key of key type Symmetric has no public half [RFC 9053, Section 7.3]!');\r\n\r\n return this.copy({ d: null, priv: null });\r\n\r\n }\r\n\r\n\r\n /** A copy of this key carrying the given algorithm. */\r\n public withAlgorithm(algorithm: CoseAlgorithm): CoseKey {\r\n return this.copy({ algorithm });\r\n }\r\n\r\n\r\n private requireCurve(): CoseCurve {\r\n\r\n if (this.keyType !== KEY_TYPE_EC2 && this.keyType !== KEY_TYPE_OKP)\r\n throw new CoseError(`A COSE key of key type ${String(this.keyType)} has no elliptic curve!`);\r\n\r\n const curve = this.curve;\r\n\r\n if (curve === null)\r\n throw new CoseError(this.curveId === null\r\n ? 'This COSE key does not name an elliptic curve!'\r\n : `The elliptic curve ${String(this.curveId)} of this COSE key is not registered!`);\r\n\r\n return curve;\r\n\r\n }\r\n\r\n\r\n /**\r\n * The public key, in whatever form its key type gives it: `04 ‖ x ‖ y` for\r\n * EC2, the whole of `x` for OKP, `pub` for AKP.\r\n */\r\n public publicKeyBytes(): Uint8Array {\r\n\r\n if (this.keyType === KEY_TYPE_SYMMETRIC)\r\n throw new CoseError('A COSE key of key type Symmetric has no public key [RFC 9053, Section 7.3]!');\r\n\r\n if (this.keyType === KEY_TYPE_AKP) {\r\n\r\n if (this.pub === null)\r\n throw new CoseError('This COSE key carries no public key!');\r\n\r\n return this.pub;\r\n\r\n }\r\n\r\n const curve = this.requireCurve();\r\n const fieldSize = curve.fieldSize ?? 0;\r\n\r\n if (this.x === null)\r\n throw new CoseError(`A COSE key on the curve '${curve.name}' needs its public key!`);\r\n\r\n if (this.keyType === KEY_TYPE_OKP) {\r\n\r\n if (this.x.length !== fieldSize)\r\n throw new CoseError(`The public key of a COSE key on the curve '${curve.name}' must be ${String(fieldSize)} bytes long, but was ${String(this.x.length)} bytes long!`);\r\n\r\n return this.x;\r\n\r\n }\r\n\r\n if (this.y === null)\r\n throw new CoseError(`A COSE key on the curve '${curve.name}' needs both of its coordinates!`);\r\n\r\n if (this.x.length !== fieldSize || this.y.length !== fieldSize)\r\n throw new CoseError(`The coordinates of a COSE key on the curve '${curve.name}' must be ${String(fieldSize)} bytes wide, including leading zeroes, but were ${String(this.x.length)} and ${String(this.y.length)} bytes wide!`);\r\n\r\n const uncompressed = new Uint8Array(1 + 2 * fieldSize);\r\n\r\n uncompressed[0] = 0x04;\r\n uncompressed.set(this.x, 1);\r\n uncompressed.set(this.y, 1 + fieldSize);\r\n\r\n if (!isOnCurve(curve, uncompressed))\r\n throw new CoseError(`The public key of this COSE key does not lie on the curve '${curve.name}'!`);\r\n\r\n return uncompressed;\r\n\r\n }\r\n\r\n\r\n /**\r\n * The secret this key holds: the scalar for EC2 and OKP, the seed for AKP,\r\n * the shared key itself for a symmetric one.\r\n */\r\n public privateKeyBytes(): Uint8Array {\r\n\r\n if (this.keyType === KEY_TYPE_SYMMETRIC) {\r\n\r\n if (this.k === null)\r\n throw new CoseError('This COSE key carries no key value!');\r\n\r\n return this.k;\r\n\r\n }\r\n\r\n if (this.keyType === KEY_TYPE_AKP) {\r\n\r\n if (this.priv === null)\r\n throw new CoseError('This COSE key carries no private key material!');\r\n\r\n if (this.priv.length !== MLDSA_SEED_SIZE)\r\n throw new CoseError(`The private key of an algorithm key pair is the seed and must be ${String(MLDSA_SEED_SIZE)} bytes long [RFC 9964], but was ${String(this.priv.length)} bytes long!`);\r\n\r\n return this.priv;\r\n\r\n }\r\n\r\n const curve = this.requireCurve();\r\n const orderSize = curve.orderSize ?? 0;\r\n\r\n if (this.d === null)\r\n throw new CoseError('This COSE key carries no private key material!');\r\n\r\n if (this.d.length !== orderSize)\r\n throw new CoseError(`The private key of a COSE key on the curve '${curve.name}' must be ${String(orderSize)} bytes wide, including leading zeroes, but was ${String(this.d.length)} bytes wide!`);\r\n\r\n if (this.keyType === KEY_TYPE_EC2 && this.d.every(each => each === 0))\r\n throw new CoseError(`The private key of this COSE key is not within the group order of the curve '${curve.name}'!`);\r\n\r\n return this.d;\r\n\r\n }\r\n\r\n\r\n /**\r\n * The input of the COSE Key Thumbprint [RFC 9679, Section 3]: the required\r\n * parameters of this key, and nothing else, in deterministic encoding.\r\n *\r\n * Leaving out the optional parameters is what makes the thumbprint an\r\n * identity rather than a checksum — the public and the private half of one\r\n * key pair produce the same value, and adding a key identifier does not\r\n * change it.\r\n *\r\n * An AKP key is the exception that proves the rule: its algorithm *is*\r\n * required [RFC 9964], because an ML-DSA public key does not say which\r\n * parameter set produced it, and two keys of different strengths must not\r\n * be able to share an identity.\r\n */\r\n public thumbprintInput(): Uint8Array {\r\n\r\n if (this.keyType === KEY_TYPE_EC2) {\r\n\r\n if (this.curveId === null || this.x === null || this.y === null)\r\n throw new CoseError('The thumbprint of a COSE key of key type EC2 needs its curve and both of its coordinates!');\r\n\r\n return cbor.encode(cbor.map([\r\n [cbor.int(KeyLabel.keyType), cbor.int(this.keyType)],\r\n [cbor.int(KeyLabel.curve), cbor.int(this.curveId)],\r\n [cbor.int(KeyLabel.x), cbor.bytes(this.x)],\r\n [cbor.int(KeyLabel.y), cbor.bytes(this.y)],\r\n ]), DETERMINISTIC);\r\n\r\n }\r\n\r\n if (this.keyType === KEY_TYPE_OKP) {\r\n\r\n if (this.curveId === null || this.x === null)\r\n throw new CoseError('The thumbprint of a COSE key of key type OKP needs its curve and its public key!');\r\n\r\n return cbor.encode(cbor.map([\r\n [cbor.int(KeyLabel.keyType), cbor.int(this.keyType)],\r\n [cbor.int(KeyLabel.curve), cbor.int(this.curveId)],\r\n [cbor.int(KeyLabel.x), cbor.bytes(this.x)],\r\n ]), DETERMINISTIC);\r\n\r\n }\r\n\r\n if (this.keyType === KEY_TYPE_AKP) {\r\n\r\n if (this.algorithm === null || this.pub === null)\r\n throw new CoseError('The thumbprint of a COSE key of key type AKP needs its algorithm and its public key!');\r\n\r\n return cbor.encode(cbor.map([\r\n [cbor.int(KeyLabel.keyType), cbor.int(this.keyType)],\r\n [cbor.int(KeyLabel.algorithm), algorithmToCbor(this.algorithm)],\r\n [cbor.int(KeyLabel.pub), cbor.bytes(this.pub)],\r\n ]), DETERMINISTIC);\r\n\r\n }\r\n\r\n if (this.keyType === KEY_TYPE_SYMMETRIC) {\r\n\r\n if (this.k === null)\r\n throw new CoseError('The thumbprint of a COSE key of key type Symmetric needs its key value!');\r\n\r\n // RFC 9679 Section 4.4 defines this, and Section 7 immediately\r\n // warns about it: the thumbprint of a symmetric key is a hash of\r\n // the secret, so a low-entropy one can simply be looked up in a\r\n // precomputed table. It is a usable identifier for a randomly\r\n // chosen key of at least 128 bits and MUST NOT be used for\r\n // passwords or anything like them.\r\n return cbor.encode(cbor.map([\r\n [cbor.int(KeyLabel.keyType), cbor.int(this.keyType)],\r\n [cbor.int(KeyLabel.k), cbor.bytes(this.k)],\r\n ]), DETERMINISTIC);\r\n\r\n }\r\n\r\n throw new CoseError(`The thumbprint of a COSE key of key type ${String(this.keyType)} is not implemented!`);\r\n\r\n }\r\n\r\n\r\n /** The COSE Key Thumbprint [RFC 9679], untruncated. */\r\n public thumbprint(hash: DigestAlgorithm = 'sha256'): Uint8Array {\r\n return digest(hash, this.thumbprintInput());\r\n }\r\n\r\n\r\n /**\r\n * The leading bytes of the thumbprint, for use as a key identifier.\r\n *\r\n * Two properties make this worth preferring over a self-chosen prefix.\r\n * Everyone holding the public key can recompute it, so no registry is\r\n * needed beyond an agreement on its length. And because the thumbprint\r\n * covers the curve — or, for an algorithm key pair, the algorithm — a\r\n * signer who changes strength necessarily has a different key and\r\n * therefore a different identifier: a downgrade under an unchanged\r\n * identity is not expressible.\r\n */\r\n public thumbprintKeyIdentifier(length = 8,\r\n hash: DigestAlgorithm = 'sha256'): Uint8Array {\r\n\r\n const value = this.thumbprint(hash);\r\n\r\n if (length < 1 || length > value.length)\r\n throw new CoseError(`A thumbprint key identifier must be between 1 and ${String(value.length)} bytes long, but ${String(length)} bytes were asked for!`);\r\n\r\n return value.slice(0, length);\r\n\r\n }\r\n\r\n\r\n /** A copy of this key whose key identifier is its own thumbprint. */\r\n public withThumbprintKeyIdentifier(length = 8,\r\n hash: DigestAlgorithm = 'sha256'): CoseKey {\r\n return this.copy({ keyIdentifier: this.thumbprintKeyIdentifier(length, hash) });\r\n }\r\n\r\n}\r\n\r\n\r\n/** The fields every key starts from, before its key type fills any in. */\r\nfunction empty(keyType: number, parts: CoseKeyParts): CoseKeyFields {\r\n return {\r\n keyType,\r\n keyIdentifier: parts.keyIdentifier ?? null,\r\n algorithm: parts.algorithm ?? null,\r\n keyOperations: null,\r\n curveId: null,\r\n x: null,\r\n y: null,\r\n d: null,\r\n pub: null,\r\n priv: null,\r\n k: null,\r\n additional: [],\r\n };\r\n}\r\n\r\n\r\nfunction bytesOf(value: CborValue, what: string): Uint8Array {\r\n\r\n if (value.type !== 'bytes')\r\n throw new CoseError(`${what} must be a byte string!`);\r\n\r\n return value.value;\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * One signature of a multi-signer message [RFC 9052, Section 4.1], and the\r\n * very same structure once more as a countersignature [RFC 9338].\r\n *\r\n * <code>\r\n * COSE_Signature = [\r\n * protected : bstr .cbor header_map,\r\n * unprotected : header_map,\r\n * signature : bstr\r\n * ]\r\n * </code>\r\n *\r\n * It carries header buckets of its own, which is what lets every party sign\r\n * with its own algorithm and its own key.\r\n */\r\n\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport { cbor, encode } from './cbor.ts';\r\nimport type { CborValue } from './cbor.ts';\r\nimport { CoseError } from './errors.ts';\r\nimport { CoseHeaders } from './headers.ts';\r\n\r\n\r\nexport class CoseSignature {\r\n\r\n /** The serialized protected bucket, exactly as signed and as received. */\r\n public readonly protectedHeaderBytes: Uint8Array;\r\n\r\n /** The protected header parameters, which this signature covers. */\r\n public readonly protectedHeader: CoseHeaders;\r\n\r\n /** The unprotected header parameters, which it does not. */\r\n public readonly unprotectedHeader: CoseHeaders;\r\n\r\n /** The signature: `r ‖ s`, never DER. */\r\n public readonly signature: Uint8Array;\r\n\r\n\r\n public constructor(protectedHeaderBytes: Uint8Array,\r\n unprotectedHeader: CoseHeaders | null,\r\n signature: Uint8Array) {\r\n\r\n this.protectedHeaderBytes = protectedHeaderBytes;\r\n this.protectedHeader = CoseHeaders.parseProtected(protectedHeaderBytes);\r\n this.unprotectedHeader = unprotectedHeader ?? CoseHeaders.empty;\r\n this.signature = signature;\r\n\r\n }\r\n\r\n\r\n /**\r\n * The signature algorithm, taken from the protected bucket and only\r\n * otherwise from the unprotected one.\r\n */\r\n public get algorithm(): CoseAlgorithm | null {\r\n return this.protectedHeader.algorithm ?? this.unprotectedHeader.algorithm;\r\n }\r\n\r\n /** The key identifier, protected bucket first. */\r\n public get keyIdentifier(): Uint8Array | null {\r\n return this.protectedHeader.keyIdentifier ?? this.unprotectedHeader.keyIdentifier;\r\n }\r\n\r\n\r\n /** Parse a three-element COSE_Signature. */\r\n public static parse(value: CborValue): CoseSignature {\r\n\r\n if (value.type !== 'array')\r\n throw new CoseError(`A COSE_Signature must be a CBOR array, but was a CBOR ${value.type}!`);\r\n\r\n if (value.items.length !== 3)\r\n throw new CoseError(`A COSE_Signature must be a CBOR array of 3 elements, but had ${String(value.items.length)} element(s)!`);\r\n\r\n const [protectedBytes, unprotected, signature] = value.items;\r\n\r\n if (protectedBytes?.type !== 'bytes')\r\n throw new CoseError('The protected header bucket of a COSE_Signature must be a byte string!');\r\n\r\n if (unprotected === undefined)\r\n throw new CoseError('A COSE_Signature must carry an unprotected header bucket!');\r\n\r\n if (signature?.type !== 'bytes')\r\n throw new CoseError('The signature of a COSE_Signature must be a byte string!');\r\n\r\n return new CoseSignature(protectedBytes.value,\r\n CoseHeaders.parse(unprotected),\r\n signature.value);\r\n\r\n }\r\n\r\n\r\n /** A CBOR representation of this signature. */\r\n public toCbor(): CborValue {\r\n\r\n return cbor.array([\r\n cbor.bytes(this.protectedHeaderBytes),\r\n this.unprotectedHeader.toCbor(),\r\n cbor.bytes(this.signature),\r\n ]);\r\n\r\n }\r\n\r\n\r\n /** The CBOR encoding of this signature. */\r\n public toBytes(): Uint8Array {\r\n return encode(this.toCbor());\r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * The two questions every verification has to answer before it can do any\r\n * arithmetic: *which algorithm*, and *over which payload*.\r\n *\r\n * Both are shared by COSE_Sign1, COSE_Sign and countersignatures, and both are\r\n * places where a permissive answer quietly destroys the guarantee. They live\r\n * here so that the three cannot drift apart.\r\n */\r\n\r\nimport { sameAlgorithm } from './algorithm.ts';\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport type { CoseHeaders } from './headers.ts';\r\n\r\n\r\n/** Either an answer, or the reason there is none. */\r\nexport type Resolved<T> =\r\n | { readonly ok: true; readonly value: T }\r\n | { readonly ok: false; readonly reason: string };\r\n\r\n\r\n/**\r\n * Which algorithm to verify with.\r\n *\r\n * An algorithm stated in the *unprotected* bucket is not covered by the\r\n * signature and can therefore be changed by anyone on the path. It is not\r\n * silently trusted: the caller has to name the expected algorithm to accept\r\n * it, deliberately, which is the difference between a verifier that resists an\r\n * algorithm-substitution attack and one that documents that it does.\r\n */\r\nexport function resolveAlgorithm(protectedHeader: CoseHeaders,\r\n unprotectedHeader: CoseHeaders,\r\n expected: CoseAlgorithm | null,\r\n what: string): Resolved<CoseAlgorithm> {\r\n\r\n const algorithm = expected ?? protectedHeader.algorithm;\r\n\r\n if (algorithm === null) {\r\n\r\n const stated = unprotectedHeader.algorithm;\r\n\r\n return {\r\n ok: false,\r\n reason: stated !== null\r\n ? `${what} states its algorithm '${stated.name}' within the unprotected header bucket only, where it is not covered by the signature: pass the expected algorithm explicitly in order to accept it!`\r\n : `${what} does not state its signature algorithm: pass the expected algorithm explicitly!`,\r\n };\r\n\r\n }\r\n\r\n const stated = protectedHeader.algorithm ?? unprotectedHeader.algorithm;\r\n\r\n if (stated !== null && !sameAlgorithm(stated, algorithm))\r\n return {\r\n ok: false,\r\n reason: `${what} was signed with the algorithm '${stated.name}', but the algorithm '${algorithm.name}' was expected!`,\r\n };\r\n\r\n return { ok: true, value: algorithm };\r\n\r\n}\r\n\r\n\r\n/**\r\n * Which payload the signature is computed over: the one carried within the\r\n * message, or the detached one supplied by the caller.\r\n *\r\n * Supplying both is rejected, because there would be no way to tell which of\r\n * the two a verification result refers to.\r\n */\r\nexport function resolvePayload(carried: Uint8Array | null,\r\n detached: Uint8Array | null,\r\n what: string): Resolved<Uint8Array> {\r\n\r\n if (carried !== null) {\r\n\r\n if (detached !== null)\r\n return { ok: false, reason: `${what} carries its payload, therefore no detached payload must be supplied!` };\r\n\r\n return { ok: true, value: carried };\r\n\r\n }\r\n\r\n if (detached === null)\r\n return { ok: false, reason: `The payload of ${what} is detached, therefore it must be supplied for the signature to be computed!` };\r\n\r\n return { ok: true, value: detached };\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * As much ASN.1 DER as an X.509 certificate needs, and not one rule more.\r\n *\r\n * This is a *reader*, never a writer: certificates arrive already encoded and\r\n * the only bytes this package ever hashes are the ones that arrived, so\r\n * re-encoding a parsed structure would be a way to get the wrong answer and\r\n * nothing else. Every node therefore keeps its own encoding, which is how\r\n * `tbsCertificate` is fed to a signature verification byte for byte.\r\n *\r\n * The rules enforced here are DER's rather than BER's, because a certificate\r\n * is DER by definition [RFC 5280, Section 4.1] and because the difference is\r\n * where parsing differentials live: an indefinite length or a non-minimal one\r\n * is the sort of thing one implementation shrugs at and another rejects, and\r\n * two implementations that disagree about where a certificate ends can be made\r\n * to disagree about what it says.\r\n *\r\n * What is deliberately absent: indefinite lengths, tags above 30 (no\r\n * multi-byte identifiers appear in a certificate), and every string type\r\n * beyond the handful X.509 names actually use.\r\n */\r\n\r\nimport { CoseError } from './errors.ts';\r\n\r\n\r\n// ------------------------------------------------------------------- tags ---\r\n\r\n/** The universal ASN.1 tags this package meets. */\r\nexport const Tag = {\r\n boolean: 0x01,\r\n integer: 0x02,\r\n bitString: 0x03,\r\n octetString: 0x04,\r\n null: 0x05,\r\n objectIdentifier: 0x06,\r\n utf8String: 0x0c,\r\n printableString: 0x13,\r\n teletexString: 0x14,\r\n ia5String: 0x16,\r\n utcTime: 0x17,\r\n generalizedTime: 0x18,\r\n bmpString: 0x1e,\r\n universalString: 0x1c,\r\n sequence: 0x30,\r\n set: 0x31,\r\n} as const;\r\n\r\n\r\n/** A context-specific constructed tag, e.g. `[0]` is `contextTag(0)`. */\r\nexport const contextTag = (number: number): number => 0xa0 | number;\r\n\r\n\r\n/** The string tags an X.509 `DirectoryString` may carry. */\r\nconst STRING_TAGS: readonly number[] = [\r\n Tag.utf8String, Tag.printableString, Tag.teletexString,\r\n Tag.ia5String, Tag.bmpString, Tag.universalString,\r\n];\r\n\r\n\r\n// ------------------------------------------------------------------ nodes ---\r\n\r\n/**\r\n * One tag-length-value record.\r\n *\r\n * `content` is the value octets and `encoded` the whole record — identifier,\r\n * length and value. Both matter: the content is what a field says, the\r\n * encoding is what a signature covers.\r\n */\r\nexport interface Asn1Node {\r\n\r\n /** The identifier octet. */\r\n readonly tag: number;\r\n\r\n /** The value octets, without identifier or length. */\r\n readonly content: Uint8Array;\r\n\r\n /** The complete record, exactly as it appeared. */\r\n readonly encoded: Uint8Array;\r\n\r\n}\r\n\r\n\r\n/**\r\n * A cursor over a sequence of DER records.\r\n *\r\n * The `what` is carried only so that a failure can say which structure was\r\n * being read; a message naming a byte offset and nothing else is a message\r\n * that has to be debugged rather than read.\r\n */\r\nexport class DerReader {\r\n\r\n private readonly data: Uint8Array;\r\n private readonly what: string;\r\n private at: number;\r\n\r\n\r\n public constructor(data: Uint8Array, what: string) {\r\n this.data = data;\r\n this.what = what;\r\n this.at = 0;\r\n }\r\n\r\n\r\n /** Whether every record has been read. */\r\n public get atEnd(): boolean {\r\n return this.at >= this.data.length;\r\n }\r\n\r\n\r\n /** The octets not yet read. */\r\n public get remaining(): Uint8Array {\r\n return this.data.subarray(this.at);\r\n }\r\n\r\n\r\n private fail(reason: string): never {\r\n throw new CoseError(`${this.what}: ${reason}`);\r\n }\r\n\r\n\r\n /**\r\n * Read the next record, optionally insisting on a tag.\r\n *\r\n * The length rules are DER's: definite always, short form below 128,\r\n * long form minimally encoded and never longer than eight octets — which\r\n * is far more than a certificate can need and still shorter than the point\r\n * where a length stops fitting a JavaScript number.\r\n */\r\n public read(expectedTag?: number): Asn1Node {\r\n\r\n const start = this.at;\r\n\r\n if (this.at + 2 > this.data.length)\r\n this.fail(`a DER record needs at least two octets, and only ${String(this.data.length - this.at)} remain`);\r\n\r\n const tag = this.data[this.at++]!;\r\n\r\n if ((tag & 0x1f) === 0x1f)\r\n this.fail('a DER identifier of more than one octet is not something a certificate contains');\r\n\r\n if (expectedTag !== undefined && tag !== expectedTag)\r\n this.fail(`expected the DER tag 0x${expectedTag.toString(16).padStart(2, '0')}, but found 0x${tag.toString(16).padStart(2, '0')}`);\r\n\r\n const first = this.data[this.at++]!;\r\n\r\n let length: number;\r\n\r\n if (first === 0x80)\r\n this.fail('an indefinite length is BER, not DER, and a certificate is DER');\r\n\r\n else if (first === 0xff)\r\n this.fail('0xFF is not a valid DER length octet');\r\n\r\n else if (first < 0x80)\r\n length = first;\r\n\r\n else {\r\n\r\n const count = first & 0x7f;\r\n\r\n if (count > 8)\r\n this.fail(`a length of ${String(count)} octets is longer than anything a certificate can hold`);\r\n\r\n if (this.at + count > this.data.length)\r\n this.fail('the long-form length runs past the end of the data');\r\n\r\n if (this.data[this.at] === 0x00)\r\n this.fail('a DER length must not be encoded with a leading zero octet');\r\n\r\n length = 0;\r\n\r\n for (let index = 0; index < count; index++)\r\n length = length * 256 + this.data[this.at++]!;\r\n\r\n if (length < 0x80)\r\n this.fail(`the length ${String(length)} must be encoded in the short form`);\r\n\r\n if (!Number.isSafeInteger(length))\r\n this.fail('the length is larger than this implementation can address');\r\n\r\n }\r\n\r\n if (this.at + length > this.data.length)\r\n this.fail(`a record claims ${String(length)} octets, and only ${String(this.data.length - this.at)} remain`);\r\n\r\n const content = this.data.subarray(this.at, this.at + length);\r\n\r\n this.at += length;\r\n\r\n return { tag, content, encoded: this.data.subarray(start, this.at) };\r\n\r\n }\r\n\r\n\r\n /** Read the next record when it carries the given tag, else read nothing. */\r\n public readOptional(tag: number): Asn1Node | null {\r\n\r\n if (this.atEnd || this.data[this.at] !== tag)\r\n return null;\r\n\r\n return this.read(tag);\r\n\r\n }\r\n\r\n\r\n /** Whether a record with the given tag comes next. */\r\n public peekIs(tag: number): boolean {\r\n return !this.atEnd && this.data[this.at] === tag;\r\n }\r\n\r\n\r\n /** Insist that nothing follows, which is how trailing data is caught. */\r\n public expectEnd(): void {\r\n\r\n if (!this.atEnd)\r\n this.fail(`${String(this.data.length - this.at)} octets follow the structure and should not`);\r\n\r\n }\r\n\r\n}\r\n\r\n\r\n/** A cursor over the contents of a constructed record. */\r\nexport const contentsOf = (node: Asn1Node, what: string): DerReader =>\r\n new DerReader(node.content, what);\r\n\r\n\r\n// ------------------------------------------------------------- primitives ---\r\n\r\n/**\r\n * A DER INTEGER as a bigint, two's complement and minimally encoded.\r\n *\r\n * Certificates hold signed integers here — a serial number is defined as one\r\n * — so a leading 0x00 before a high bit is padding and a leading 0x00 before\r\n * anything else is a violation.\r\n */\r\nexport function derInteger(node: Asn1Node, what: string): bigint {\r\n\r\n const bytes = node.content;\r\n\r\n if (bytes.length === 0)\r\n throw new CoseError(`${what}: a DER INTEGER must not be empty`);\r\n\r\n if (bytes.length > 1 &&\r\n ((bytes[0] === 0x00 && (bytes[1]! & 0x80) === 0) ||\r\n (bytes[0] === 0xff && (bytes[1]! & 0x80) !== 0)))\r\n throw new CoseError(`${what}: a DER INTEGER must be minimally encoded`);\r\n\r\n let value = 0n;\r\n\r\n for (const each of bytes)\r\n value = (value << 8n) | BigInt(each);\r\n\r\n // Negative when the high bit of the first octet is set.\r\n return (bytes[0]! & 0x80) === 0\r\n ? value\r\n : value - (1n << BigInt(8 * bytes.length));\r\n\r\n}\r\n\r\n\r\n/**\r\n * A DER BIT STRING, as whole octets.\r\n *\r\n * Every bit string a certificate carries a key or a signature in is octet\r\n * aligned, so an unused-bit count other than zero is refused rather than\r\n * shifted — `keyUsage` is the one exception and reads the count itself.\r\n */\r\nexport function derBitString(node: Asn1Node, what: string): Uint8Array {\r\n\r\n const { unusedBits, bytes } = derBitStringRaw(node, what);\r\n\r\n if (unusedBits !== 0)\r\n throw new CoseError(`${what}: expected an octet-aligned BIT STRING, but ${String(unusedBits)} bits are unused`);\r\n\r\n return bytes;\r\n\r\n}\r\n\r\n\r\n/** A DER BIT STRING with its unused-bit count, which `keyUsage` needs. */\r\nexport function derBitStringRaw(node: Asn1Node, what: string): { unusedBits: number; bytes: Uint8Array } {\r\n\r\n if (node.content.length === 0)\r\n throw new CoseError(`${what}: a DER BIT STRING needs at least its unused-bit count`);\r\n\r\n const unusedBits = node.content[0]!;\r\n\r\n if (unusedBits > 7)\r\n throw new CoseError(`${what}: a DER BIT STRING can not have ${String(unusedBits)} unused bits`);\r\n\r\n if (unusedBits !== 0 && node.content.length === 1)\r\n throw new CoseError(`${what}: an empty DER BIT STRING must declare zero unused bits`);\r\n\r\n return { unusedBits, bytes: node.content.subarray(1) };\r\n\r\n}\r\n\r\n\r\n/** A DER BOOLEAN. DER admits exactly two encodings, and 0x01 is not one of them. */\r\nexport function derBoolean(node: Asn1Node, what: string): boolean {\r\n\r\n if (node.content.length !== 1)\r\n throw new CoseError(`${what}: a DER BOOLEAN is one octet`);\r\n\r\n if (node.content[0] === 0x00)\r\n return false;\r\n\r\n if (node.content[0] === 0xff)\r\n return true;\r\n\r\n throw new CoseError(`${what}: a DER BOOLEAN is 0x00 or 0xFF, but was 0x${node.content[0]!.toString(16).padStart(2, '0')}`);\r\n\r\n}\r\n\r\n\r\n/**\r\n * A DER OBJECT IDENTIFIER, in dotted decimal.\r\n *\r\n * The first two arcs share one octet — `40·first + second` — which is why\r\n * `2.16.840…` and `1.2.840…` both begin with a byte in the eighties, and why\r\n * the first arc is recovered by division rather than by lookup.\r\n */\r\nexport function derObjectIdentifier(node: Asn1Node, what: string): string {\r\n\r\n const bytes = node.content;\r\n\r\n if (bytes.length === 0)\r\n throw new CoseError(`${what}: a DER OBJECT IDENTIFIER must not be empty`);\r\n\r\n const arcs: string[] = [];\r\n\r\n let value = 0n;\r\n let started = false;\r\n\r\n for (let index = 0; index < bytes.length; index++) {\r\n\r\n const octet = bytes[index]!;\r\n\r\n if (!started && octet === 0x80)\r\n throw new CoseError(`${what}: an arc of a DER OBJECT IDENTIFIER must be minimally encoded`);\r\n\r\n started = true;\r\n value = (value << 7n) | BigInt(octet & 0x7f);\r\n\r\n if ((octet & 0x80) !== 0) {\r\n\r\n if (index === bytes.length - 1)\r\n throw new CoseError(`${what}: a DER OBJECT IDENTIFIER ends in the middle of an arc`);\r\n\r\n continue;\r\n\r\n }\r\n\r\n if (arcs.length === 0) {\r\n\r\n // 0.x is below 40, 1.x below 80, 2.x everything above — and 2.x\r\n // is unbounded, so the third case has no upper limit to check.\r\n const first = value < 40n ? 0n : value < 80n ? 1n : 2n;\r\n\r\n arcs.push(first.toString());\r\n arcs.push((value - first * 40n).toString());\r\n\r\n }\r\n\r\n else\r\n arcs.push(value.toString());\r\n\r\n value = 0n;\r\n started = false;\r\n\r\n }\r\n\r\n return arcs.join('.');\r\n\r\n}\r\n\r\n\r\n/** A DER string, in whichever of the X.509 string types it was written. */\r\nexport function derString(node: Asn1Node, what: string): string {\r\n\r\n if (!STRING_TAGS.includes(node.tag))\r\n throw new CoseError(`${what}: 0x${node.tag.toString(16).padStart(2, '0')} is not a string type an X.509 name may use`);\r\n\r\n // BMPString is UTF-16BE and UniversalString UTF-32BE; both are rare and\r\n // both appear in the wild, so neither is worth refusing.\r\n if (node.tag === Tag.bmpString)\r\n return decodeWide(node.content, 2, what);\r\n\r\n if (node.tag === Tag.universalString)\r\n return decodeWide(node.content, 4, what);\r\n\r\n // TeletexString is Latin-1 in every certificate anybody actually issues.\r\n if (node.tag === Tag.teletexString)\r\n return Array.from(node.content, each => String.fromCharCode(each)).join('');\r\n\r\n try {\r\n return new TextDecoder('utf-8', { fatal: true }).decode(node.content);\r\n }\r\n catch {\r\n // `fatal: true` makes the platform throw its own TypeError, which was\r\n // the one untyped escape this reader had — found by the fuzz suite,\r\n // and a hostile certificate is exactly who sends invalid UTF-8.\r\n throw new CoseError(`${what}: the content is not valid UTF-8`);\r\n }\r\n\r\n}\r\n\r\n\r\nfunction decodeWide(bytes: Uint8Array, width: number, what: string): string {\r\n\r\n if (bytes.length % width !== 0)\r\n throw new CoseError(`${what}: a ${String(width * 8)}-bit string must be a whole number of characters`);\r\n\r\n let text = '';\r\n\r\n for (let index = 0; index < bytes.length; index += width) {\r\n\r\n let point = 0;\r\n\r\n for (let byte = 0; byte < width; byte++)\r\n point = point * 256 + bytes[index + byte]!;\r\n\r\n // Refused rather than passed to the platform: String.fromCodePoint\r\n // answers a value beyond U+10FFFF with a RangeError of its own, which\r\n // would be an untyped escape. (Appending one character at a time is\r\n // deliberate too — a spread over the whole array is a stack overflow\r\n // waiting for a large enough string.)\r\n if (point > 0x10FFFF)\r\n throw new CoseError(`${what}: 0x${point.toString(16)} is not a Unicode code point`);\r\n\r\n text += String.fromCodePoint(point);\r\n\r\n }\r\n\r\n return text;\r\n\r\n}\r\n\r\n\r\n/**\r\n * A DER UTCTime or GeneralizedTime.\r\n *\r\n * DER admits exactly one form of each: seconds present, no fractional part,\r\n * and Zulu — so anything else is refused rather than guessed at. The\r\n * two-digit year of a UTCTime is windowed as RFC 5280 Section 4.1.2.5.1\r\n * requires, 50 and above being the twentieth century.\r\n */\r\nexport function derTime(node: Asn1Node, what: string): Date {\r\n\r\n const text = Array.from(node.content, each => String.fromCharCode(each)).join('');\r\n\r\n if (node.tag === Tag.utcTime) {\r\n\r\n const match = /^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(text);\r\n\r\n if (match === null)\r\n throw new CoseError(`${what}: '${text}' is not a DER UTCTime of the form YYMMDDHHMMSSZ`);\r\n\r\n const year = Number(match[1]);\r\n\r\n return utc(year >= 50 ? 1900 + year : 2000 + year,\r\n Number(match[2]), Number(match[3]),\r\n Number(match[4]), Number(match[5]), Number(match[6]),\r\n text, what);\r\n\r\n }\r\n\r\n if (node.tag === Tag.generalizedTime) {\r\n\r\n const match = /^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(text);\r\n\r\n if (match === null)\r\n throw new CoseError(`${what}: '${text}' is not a DER GeneralizedTime of the form YYYYMMDDHHMMSSZ`);\r\n\r\n return utc(Number(match[1]), Number(match[2]), Number(match[3]),\r\n Number(match[4]), Number(match[5]), Number(match[6]),\r\n text, what);\r\n\r\n }\r\n\r\n throw new CoseError(`${what}: 0x${node.tag.toString(16).padStart(2, '0')} is not a time type`);\r\n\r\n}\r\n\r\n\r\n/**\r\n * Build a UTC instant, refusing what `Date.UTC` would otherwise roll over.\r\n *\r\n * `Date.UTC(2026, 1, 31)` is the 3rd of March and reports no error at all,\r\n * which is exactly the wrong behaviour for a validity period: a certificate\r\n * claiming to expire on the 31st of February would silently gain two days.\r\n */\r\nfunction utc(year: number, month: number, day: number,\r\n hour: number, minute: number, second: number,\r\n text: string, what: string): Date {\r\n\r\n const value = new Date(Date.UTC(year, month - 1, day, hour, minute, second));\r\n\r\n if (value.getUTCFullYear() !== year || value.getUTCMonth() !== month - 1 ||\r\n value.getUTCDate() !== day || value.getUTCHours() !== hour ||\r\n value.getUTCMinutes() !== minute || value.getUTCSeconds() !== second)\r\n throw new CoseError(`${what}: '${text}' is not a point in time that exists`);\r\n\r\n return value;\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * X.509 certificates [RFC 5280], to the depth COSE needs them.\r\n *\r\n * COSE reaches X.509 through the header parameters of RFC 9360, and a chain\r\n * that travels in a message is untrusted input like everything else in it.\r\n * Reading one therefore means parsing it, walking it to an anchor, and — the\r\n * step that is easy to leave out — establishing that the key it ends in is the\r\n * key that actually signed. This module does the first of those; `x5chain.ts`\r\n * does the second, and `CoseSign1.verifyWithCertificateChain` the third.\r\n *\r\n * Why this is written out rather than taken from a library: verification here\r\n * has to reach every algorithm this package signs with, and that includes the\r\n * brainpool curves and the three ML-DSA parameter sets. The obvious\r\n * TypeScript X.509 libraries verify through WebCrypto, which supports neither\r\n * — so a certificate issued to a meter on brainpoolP256r1, which is the whole\r\n * point of the exercise, is exactly the certificate they cannot check. The\r\n * signature verification here goes through the same code path as every other\r\n * signature this package verifies, so whatever COSE can verify, a certificate\r\n * can be signed with.\r\n *\r\n * What is NOT done, matching Styx so that the two agree about what an answer\r\n * means: no revocation, no name constraints, no certificate policies, no path\r\n * length beyond the CA flag itself. And a certificate says \"this key belongs\r\n * to that subject, attested by someone I trust\" — whether the subject may\r\n * state what it states is never a question a certificate answers.\r\n */\r\n\r\nimport { contentsOf, contextTag, derBitString, derBitStringRaw,\r\n derBoolean, derInteger, derObjectIdentifier, derString,\r\n derTime, DerReader, Tag } from './asn1.ts';\r\nimport type { Asn1Node } from './asn1.ts';\r\nimport { CoseAlgorithms, verifyWith } from './algorithm.ts';\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport { CoseCurves } from './curve.ts';\r\nimport type { CoseCurve } from './curve.ts';\r\nimport { decompressY, digest } from './ecdsa.ts';\r\nimport type { DigestAlgorithm } from './ecdsa.ts';\r\nimport { CoseError, notVerified,\r\n VERIFIED } from './errors.ts';\r\nimport type { Verification } from './errors.ts';\r\nimport { CoseKey } from './key.ts';\r\n\r\n\r\n// ------------------------------------------------------------------- OIDs ---\r\n\r\n/** The named curves of a `SubjectPublicKeyInfo`, by object identifier. */\r\nconst CURVE_OIDS: Readonly<Record<string, CoseCurve>> = {\r\n '1.2.840.10045.3.1.7': CoseCurves.P256, // prime256v1\r\n '1.3.132.0.34': CoseCurves.P384, // secp384r1\r\n '1.3.132.0.35': CoseCurves.P521, // secp521r1\r\n '1.3.132.0.10': CoseCurves.secp256k1,\r\n '1.3.36.3.3.2.8.1.1.7': CoseCurves.brainpoolP256r1, // [RFC 5639, Appendix A]\r\n '1.3.36.3.3.2.8.1.1.9': CoseCurves.brainpoolP320r1,\r\n '1.3.36.3.3.2.8.1.1.11': CoseCurves.brainpoolP384r1,\r\n '1.3.36.3.3.2.8.1.1.13': CoseCurves.brainpoolP512r1,\r\n};\r\n\r\nconst OID_EC_PUBLIC_KEY = '1.2.840.10045.2.1';\r\nconst OID_ED25519 = '1.3.101.112';\r\nconst OID_ED448 = '1.3.101.113';\r\n\r\n/**\r\n * The ML-DSA identifiers of the NIST arc [FIPS 204, RFC 9881]. One object\r\n * identifier serves as both the key type and the signature algorithm, which is\r\n * what a fully-specified algorithm looks like in ASN.1.\r\n */\r\nconst OID_MLDSA44 = '2.16.840.1.101.3.4.3.17';\r\nconst OID_MLDSA65 = '2.16.840.1.101.3.4.3.18';\r\nconst OID_MLDSA87 = '2.16.840.1.101.3.4.3.19';\r\n\r\n/**\r\n * How a certificate's signature was produced.\r\n *\r\n * ECDSA identifiers name the digest and leave the curve to the issuer's key,\r\n * exactly as the COSE algorithms this maps them to do — which is why the\r\n * curve-less `ES*` identifiers are the right target here and the fully\r\n * specified `ESP*`/`ESB*` ones are not.\r\n */\r\nconst SIGNATURE_OIDS: Readonly<Record<string, CoseAlgorithm>> = {\r\n '1.2.840.10045.4.3.2': CoseAlgorithms.ES256, // ecdsa-with-SHA256\r\n '1.2.840.10045.4.3.3': CoseAlgorithms.ES384, // ecdsa-with-SHA384\r\n '1.2.840.10045.4.3.4': CoseAlgorithms.ES512, // ecdsa-with-SHA512\r\n [OID_ED25519]: CoseAlgorithms.Ed25519,\r\n [OID_ED448]: CoseAlgorithms.Ed448,\r\n [OID_MLDSA44]: CoseAlgorithms.MLDSA44,\r\n [OID_MLDSA65]: CoseAlgorithms.MLDSA65,\r\n [OID_MLDSA87]: CoseAlgorithms.MLDSA87,\r\n};\r\n\r\n/** The attribute types a distinguished name is usually written with. */\r\nconst NAME_OIDS: Readonly<Record<string, string>> = {\r\n '2.5.4.3': 'CN',\r\n '2.5.4.4': 'SN',\r\n '2.5.4.5': 'SERIALNUMBER',\r\n '2.5.4.6': 'C',\r\n '2.5.4.7': 'L',\r\n '2.5.4.8': 'ST',\r\n '2.5.4.9': 'STREET',\r\n '2.5.4.10': 'O',\r\n '2.5.4.11': 'OU',\r\n '2.5.4.12': 'T',\r\n '2.5.4.42': 'GIVENNAME',\r\n '1.2.840.113549.1.9.1': 'E',\r\n '0.9.2342.19200300.100.1.25': 'DC',\r\n '0.9.2342.19200300.100.1.1': 'UID',\r\n};\r\n\r\nconst OID_BASIC_CONSTRAINTS = '2.5.29.19';\r\nconst OID_KEY_USAGE = '2.5.29.15';\r\n\r\n\r\n// ------------------------------------------------------------------ names ---\r\n\r\n/** One attribute of a distinguished name. */\r\nexport interface NameAttribute {\r\n\r\n /** The attribute type, in dotted decimal. */\r\n readonly oid: string;\r\n\r\n /** The attribute value, as text. */\r\n readonly value: string;\r\n\r\n}\r\n\r\n\r\n/**\r\n * A distinguished name.\r\n *\r\n * Two names are compared the way RFC 5280 Section 7.1 asks for rather than by\r\n * their encodings: a `PrintableString` and a `UTF8String` holding the same\r\n * characters name the same entity, and a chain whose issuer field was written\r\n * in one and whose subject field was written in the other is a chain, not a\r\n * forgery. Byte equality is still tried first, because it is both cheaper and\r\n * the case that almost always applies.\r\n */\r\nexport class X509Name {\r\n\r\n /** The attributes, outermost relative name first, as they were encoded. */\r\n public readonly attributes: readonly NameAttribute[];\r\n\r\n /** The DER encoding, kept because a name is also compared by its bytes. */\r\n public readonly encoded: Uint8Array;\r\n\r\n\r\n public constructor(attributes: readonly NameAttribute[], encoded: Uint8Array) {\r\n this.attributes = attributes;\r\n this.encoded = encoded;\r\n }\r\n\r\n\r\n /** Parse an X.501 `Name`, which is a `SEQUENCE OF SET OF` attributes. */\r\n public static parse(node: Asn1Node, what: string): X509Name {\r\n\r\n const attributes: NameAttribute[] = [];\r\n const relatives = contentsOf(node, `${what}: the relative distinguished names`);\r\n\r\n while (!relatives.atEnd) {\r\n\r\n const set = relatives.read(Tag.set);\r\n const members = contentsOf(set, `${what}: a relative distinguished name`);\r\n\r\n while (!members.atEnd) {\r\n\r\n const pair = contentsOf(members.read(Tag.sequence), `${what}: an attribute of the name`);\r\n const oid = derObjectIdentifier(pair.read(Tag.objectIdentifier), `${what}: an attribute type`);\r\n const value = pair.read();\r\n\r\n pair.expectEnd();\r\n\r\n attributes.push({ oid, value: derString(value, `${what}: the value of the attribute ${oid}`) });\r\n\r\n }\r\n\r\n }\r\n\r\n return new X509Name(attributes, node.encoded);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Whether this name and the given one name the same entity.\r\n *\r\n * The normalization is the practical part of RFC 4518: leading and\r\n * trailing whitespace removed, internal runs collapsed to one space, and\r\n * case folded. Not implemented, because no certificate in this project's\r\n * world uses them: the Unicode mapping and prohibition tables.\r\n */\r\n public equivalentTo(other: X509Name): boolean {\r\n\r\n if (bytesEqual(this.encoded, other.encoded))\r\n return true;\r\n\r\n if (this.attributes.length !== other.attributes.length)\r\n return false;\r\n\r\n return this.attributes.every((each, index) =>\r\n each.oid === other.attributes[index]!.oid &&\r\n normalize(each.value) === normalize(other.attributes[index]!.value));\r\n\r\n }\r\n\r\n\r\n /** The name in the usual `CN=…,O=…` notation. */\r\n public toString(): string {\r\n\r\n return this.attributes\r\n .map(each => `${NAME_OIDS[each.oid] ?? each.oid}=${each.value}`)\r\n .join(',');\r\n\r\n }\r\n\r\n}\r\n\r\n\r\nconst normalize = (value: string): string =>\r\n value.trim().replace(/\\s+/gu, ' ').toLowerCase();\r\n\r\n\r\nconst bytesEqual = (left: Uint8Array, right: Uint8Array): boolean =>\r\n left.length === right.length && left.every((each, index) => each === right[index]);\r\n\r\n\r\n// ------------------------------------------------------------- extensions ---\r\n\r\n/** The `basicConstraints` extension [RFC 5280, Section 4.2.1.9]. */\r\nexport interface BasicConstraints {\r\n\r\n /** Whether the certified key may sign other certificates. */\r\n readonly certificateAuthority: boolean;\r\n\r\n /** How many intermediates may follow, when the extension says. */\r\n readonly pathLength: number | null;\r\n\r\n}\r\n\r\n\r\n/**\r\n * The bits of the `keyUsage` extension [RFC 5280, Section 4.2.1.3], by name.\r\n *\r\n * The order is the ASN.1 one and it is load bearing: `digitalSignature` is bit\r\n * zero and `keyCertSign` bit five, and those two are the only ones a signature\r\n * with a certificate chain turns on.\r\n */\r\nexport const KeyUsage = {\r\n digitalSignature: 0,\r\n nonRepudiation: 1,\r\n keyEncipherment: 2,\r\n dataEncipherment: 3,\r\n keyAgreement: 4,\r\n keyCertSign: 5,\r\n cRLSign: 6,\r\n encipherOnly: 7,\r\n decipherOnly: 8,\r\n} as const;\r\n\r\n\r\n// ------------------------------------------------------------ certificate ---\r\n\r\n/**\r\n * An X.509 certificate.\r\n *\r\n * Everything here is what the certificate *says*. None of it is a reason to\r\n * believe any of it: that comes from a chain to an anchor, which is\r\n * `CoseCertificateChain`'s business.\r\n */\r\nexport class X509Certificate {\r\n\r\n /** The DER encoding, exactly as it arrived. */\r\n public readonly encoded: Uint8Array;\r\n\r\n /** The `tbsCertificate`, which is the part the signature covers. */\r\n public readonly tbsBytes: Uint8Array;\r\n\r\n /** The version, 1 to 3. */\r\n public readonly version: number;\r\n\r\n /** The serial number, which may be negative and is often very large. */\r\n public readonly serialNumber: bigint;\r\n\r\n /** Who issued this certificate. */\r\n public readonly issuer: X509Name;\r\n\r\n /** Whom it was issued to. */\r\n public readonly subject: X509Name;\r\n\r\n /** The start of the validity period, inclusive. */\r\n public readonly notBefore: Date;\r\n\r\n /** The end of the validity period, inclusive. */\r\n public readonly notAfter: Date;\r\n\r\n /** The certified public key. */\r\n public readonly publicKey: CoseKey;\r\n\r\n /** How this certificate was signed, as the COSE algorithm it corresponds to. */\r\n public readonly signatureAlgorithm: CoseAlgorithm;\r\n\r\n /** The signature, as it was encoded — DER for ECDSA, raw otherwise. */\r\n public readonly signatureValue: Uint8Array;\r\n\r\n /** The `basicConstraints` extension, when present. */\r\n public readonly basicConstraints: BasicConstraints | null;\r\n\r\n /** The `keyUsage` extension as a bit array, when present. */\r\n public readonly keyUsage: readonly boolean[] | null;\r\n\r\n /** The object identifiers of every extension marked critical. */\r\n public readonly criticalExtensions: readonly string[];\r\n\r\n\r\n private constructor(fields: {\r\n encoded: Uint8Array;\r\n tbsBytes: Uint8Array;\r\n version: number;\r\n serialNumber: bigint;\r\n issuer: X509Name;\r\n subject: X509Name;\r\n notBefore: Date;\r\n notAfter: Date;\r\n publicKey: CoseKey;\r\n signatureAlgorithm: CoseAlgorithm;\r\n signatureValue: Uint8Array;\r\n basicConstraints: BasicConstraints | null;\r\n keyUsage: readonly boolean[] | null;\r\n criticalExtensions: readonly string[];\r\n }) {\r\n this.encoded = fields.encoded;\r\n this.tbsBytes = fields.tbsBytes;\r\n this.version = fields.version;\r\n this.serialNumber = fields.serialNumber;\r\n this.issuer = fields.issuer;\r\n this.subject = fields.subject;\r\n this.notBefore = fields.notBefore;\r\n this.notAfter = fields.notAfter;\r\n this.publicKey = fields.publicKey;\r\n this.signatureAlgorithm = fields.signatureAlgorithm;\r\n this.signatureValue = fields.signatureValue;\r\n this.basicConstraints = fields.basicConstraints;\r\n this.keyUsage = fields.keyUsage;\r\n this.criticalExtensions = fields.criticalExtensions;\r\n }\r\n\r\n\r\n // ------------------------------------------------------------- parsing\r\n\r\n /**\r\n * Parse a DER encoded certificate.\r\n *\r\n * The `signatureAlgorithm` of the outer structure and the `signature`\r\n * field inside the `tbsCertificate` must agree, and it is checked: they\r\n * are the same statement written twice, and an implementation that reads\r\n * one while verifying with the other can be told two different things at\r\n * once.\r\n */\r\n public static parse(der: Uint8Array): X509Certificate {\r\n\r\n const what = 'This X.509 certificate';\r\n const outer = new DerReader(der, what);\r\n const certificate = outer.read(Tag.sequence);\r\n\r\n outer.expectEnd();\r\n\r\n const body = contentsOf(certificate, what);\r\n const tbs = body.read(Tag.sequence);\r\n const outerAlgorithmNode = body.read(Tag.sequence);\r\n const signatureNode = body.read(Tag.bitString);\r\n\r\n body.expectEnd();\r\n\r\n const outerAlgorithm = algorithmIdentifier(outerAlgorithmNode, `${what}: the signature algorithm`);\r\n const fields = contentsOf(tbs, `${what}: the certificate body`);\r\n\r\n // The version is [0] EXPLICIT and defaults to v1 when absent, which\r\n // is the only reason it is optional.\r\n const versionNode = fields.readOptional(contextTag(0));\r\n const version = versionNode === null\r\n ? 1\r\n : Number(derInteger(contentsOf(versionNode, `${what}: the version`).read(Tag.integer),\r\n `${what}: the version`)) + 1;\r\n\r\n if (version < 1 || version > 3)\r\n throw new CoseError(`${what}: the version v${String(version)} is not one X.509 defines`);\r\n\r\n const serialNumber = derInteger(fields.read(Tag.integer), `${what}: the serial number`);\r\n const innerAlgorithm = algorithmIdentifier(fields.read(Tag.sequence), `${what}: the inner signature algorithm`);\r\n const issuer = X509Name.parse(fields.read(Tag.sequence), `${what}: the issuer`);\r\n\r\n const validity = contentsOf(fields.read(Tag.sequence), `${what}: the validity period`);\r\n const notBefore = derTime(validity.read(), `${what}: the start of the validity period`);\r\n const notAfter = derTime(validity.read(), `${what}: the end of the validity period`);\r\n\r\n validity.expectEnd();\r\n\r\n const subject = X509Name.parse(fields.read(Tag.sequence), `${what}: the subject`);\r\n const publicKey = subjectPublicKey(fields.read(Tag.sequence), what);\r\n\r\n if (outerAlgorithm.oid !== innerAlgorithm.oid)\r\n throw new CoseError(`${what}: says it was signed with '${outerAlgorithm.oid}' on the outside and with '${innerAlgorithm.oid}' within the body it signed`);\r\n\r\n const algorithm = SIGNATURE_OIDS[outerAlgorithm.oid];\r\n\r\n if (algorithm === undefined)\r\n throw new CoseError(`${what}: was signed with '${outerAlgorithm.oid}', which is not a signature algorithm this implementation knows`);\r\n\r\n // The unique identifiers of v2 are read past rather than kept: no\r\n // certificate anybody issues carries them, and skipping a field one\r\n // does not understand is not the same as ignoring it.\r\n fields.readOptional(0x81);\r\n fields.readOptional(0x82);\r\n\r\n const extensionsNode = fields.readOptional(contextTag(3));\r\n const extensions = extensionsNode === null\r\n ? { basicConstraints: null, keyUsage: null, critical: [] as string[] }\r\n : parseExtensions(extensionsNode, what);\r\n\r\n fields.expectEnd();\r\n\r\n if (extensionsNode !== null && version !== 3)\r\n throw new CoseError(`${what}: carries extensions, which only a v3 certificate may`);\r\n\r\n return new X509Certificate({\r\n encoded: certificate.encoded,\r\n tbsBytes: tbs.encoded,\r\n version,\r\n serialNumber,\r\n issuer,\r\n subject,\r\n notBefore,\r\n notAfter,\r\n publicKey,\r\n signatureAlgorithm: algorithm,\r\n signatureValue: derBitString(signatureNode, `${what}: the signature`),\r\n basicConstraints: extensions.basicConstraints,\r\n keyUsage: extensions.keyUsage,\r\n criticalExtensions: extensions.critical,\r\n });\r\n\r\n }\r\n\r\n\r\n // -------------------------------------------------------------- checks\r\n\r\n /** Whether this certificate is within its validity period at the given instant. */\r\n public isValidAt(at: Date): Verification {\r\n\r\n if (at.getTime() < this.notBefore.getTime())\r\n return notVerified(`The certificate '${this.subject.toString()}' is not valid before ${iso(this.notBefore)}, and was checked at ${iso(at)}!`);\r\n\r\n if (at.getTime() > this.notAfter.getTime())\r\n return notVerified(`The certificate '${this.subject.toString()}' expired at ${iso(this.notAfter)}, and was checked at ${iso(at)}!`);\r\n\r\n return VERIFIED;\r\n\r\n }\r\n\r\n\r\n /** Whether the given key usage bit is set, an absent extension meaning unrestricted. */\r\n public allows(usage: number): boolean {\r\n\r\n if (this.keyUsage === null)\r\n return true;\r\n\r\n return this.keyUsage[usage] ?? false;\r\n\r\n }\r\n\r\n\r\n /** Whether the certified key may sign other certificates. */\r\n public get isCertificateAuthority(): boolean {\r\n\r\n return this.basicConstraints?.certificateAuthority ?? false;\r\n\r\n }\r\n\r\n\r\n /**\r\n * Whether this certificate was signed by the given one.\r\n *\r\n * Both halves are checked and neither implies the other: the issuer field\r\n * has to name the candidate's subject, and the signature has to verify\r\n * with the candidate's key. A name that matches without a signature is a\r\n * claim, and a signature that verifies under a different name is somebody\r\n * else's certificate.\r\n */\r\n public verifySignedBy(issuer: X509Certificate): Verification {\r\n\r\n if (!this.issuer.equivalentTo(issuer.subject))\r\n return notVerified(`The certificate '${this.subject.toString()}' names the issuer '${this.issuer.toString()}', which is not the subject of '${issuer.subject.toString()}'!`);\r\n\r\n const key = issuer.publicKey;\r\n\r\n let signature: Uint8Array;\r\n\r\n try {\r\n signature = this.signatureAlgorithm.family === 'ecdsa'\r\n ? rawEcdsaSignature(this.signatureValue, key.curve, this.subject.toString())\r\n : this.signatureValue;\r\n }\r\n catch (exception) {\r\n return notVerified(exception instanceof Error ? exception.message : String(exception));\r\n }\r\n\r\n let verified: boolean;\r\n\r\n try {\r\n verified = verifyWith(this.signatureAlgorithm,\r\n key.curve,\r\n this.tbsBytes,\r\n signature,\r\n key.publicKeyBytes());\r\n }\r\n catch (exception) {\r\n return notVerified(`The certificate '${this.subject.toString()}' could not be checked against '${issuer.subject.toString()}': ${exception instanceof Error ? exception.message : String(exception)}`);\r\n }\r\n\r\n return verified\r\n ? VERIFIED\r\n : notVerified(`The certificate '${this.subject.toString()}' was not signed by '${issuer.subject.toString()}'!`);\r\n\r\n }\r\n\r\n\r\n /** The hash of this certificate's DER encoding, which is what `x5t` carries. */\r\n public thumbprint(hash: DigestAlgorithm = 'sha256'): Uint8Array {\r\n return digest(hash, this.encoded);\r\n }\r\n\r\n\r\n /** Whether this is byte for byte the same certificate as the given one. */\r\n public equals(other: X509Certificate): boolean {\r\n return bytesEqual(this.encoded, other.encoded);\r\n }\r\n\r\n\r\n public toString(): string {\r\n return this.subject.toString();\r\n }\r\n\r\n}\r\n\r\n\r\nconst iso = (value: Date): string => value.toISOString().replace(/\\.\\d{3}Z$/u, 'Z');\r\n\r\n\r\n// ---------------------------------------------------------------- helpers ---\r\n\r\n/** An `AlgorithmIdentifier`: an object identifier and whatever it parameterizes. */\r\nfunction algorithmIdentifier(node: Asn1Node, what: string): { oid: string; parameters: Asn1Node | null } {\r\n\r\n const fields = contentsOf(node, what);\r\n const oid = derObjectIdentifier(fields.read(Tag.objectIdentifier), what);\r\n\r\n const parameters = fields.atEnd ? null : fields.read();\r\n\r\n fields.expectEnd();\r\n\r\n return { oid, parameters };\r\n\r\n}\r\n\r\n\r\n/**\r\n * A `SubjectPublicKeyInfo`, as the COSE key it corresponds to.\r\n *\r\n * The three key types diverge here exactly as they do in COSE: an elliptic\r\n * curve key names its curve in the algorithm parameters and carries a point,\r\n * an Edwards key is its own algorithm and carries the whole public key, and an\r\n * ML-DSA key names its parameter set in the algorithm identifier — which is\r\n * the same reason an AKP COSE key has to carry `alg`.\r\n */\r\nfunction subjectPublicKey(node: Asn1Node, what: string): CoseKey {\r\n\r\n const fields = contentsOf(node, `${what}: the subject public key info`);\r\n const algorithm = algorithmIdentifier(fields.read(Tag.sequence), `${what}: the public key algorithm`);\r\n const bits = derBitString(fields.read(Tag.bitString), `${what}: the public key`);\r\n\r\n fields.expectEnd();\r\n\r\n if (algorithm.oid === OID_EC_PUBLIC_KEY) {\r\n\r\n if (algorithm.parameters === null)\r\n throw new CoseError(`${what}: holds an elliptic curve key that does not name its curve, which this implementation does not support`);\r\n\r\n if (algorithm.parameters.tag !== Tag.objectIdentifier)\r\n throw new CoseError(`${what}: holds an elliptic curve key whose parameters are not a named curve, which this implementation does not support`);\r\n\r\n const oid = derObjectIdentifier(algorithm.parameters, `${what}: the curve`);\r\n const curve = CURVE_OIDS[oid];\r\n\r\n if (curve === undefined)\r\n throw new CoseError(`${what}: holds a key on the curve '${oid}', which is not a curve this implementation knows`);\r\n\r\n return ecPublicKey(curve, bits, what);\r\n\r\n }\r\n\r\n if (algorithm.oid === OID_ED25519)\r\n return CoseKey.fromOkpPublicKey(CoseCurves.Ed25519, bits,\r\n { algorithm: CoseAlgorithms.Ed25519 });\r\n\r\n if (algorithm.oid === OID_ED448)\r\n return CoseKey.fromOkpPublicKey(CoseCurves.Ed448, bits,\r\n { algorithm: CoseAlgorithms.Ed448 });\r\n\r\n const mldsa = algorithm.oid === OID_MLDSA44 ? CoseAlgorithms.MLDSA44\r\n : algorithm.oid === OID_MLDSA65 ? CoseAlgorithms.MLDSA65\r\n : algorithm.oid === OID_MLDSA87 ? CoseAlgorithms.MLDSA87\r\n : null;\r\n\r\n if (mldsa !== null)\r\n return CoseKey.fromAkpPublicKey(mldsa, bits);\r\n\r\n throw new CoseError(`${what}: holds a key of type '${algorithm.oid}', which is not a key type this implementation knows`);\r\n\r\n}\r\n\r\n\r\n/**\r\n * An elliptic curve point as a COSE key.\r\n *\r\n * Uncompressed is what every certificate in practice carries; compressed is\r\n * accepted because RFC 5480 permits it and because the curve arithmetic to\r\n * recover `y` is already here for COSE keys, which permit it too.\r\n */\r\nfunction ecPublicKey(curve: CoseCurve, point: Uint8Array, what: string): CoseKey {\r\n\r\n const width = curve.fieldSize;\r\n\r\n if (width === null)\r\n throw new CoseError(`${what}: holds a key on the curve '${curve.name}', which has no signature algorithm`);\r\n\r\n if (point.length === 0)\r\n throw new CoseError(`${what}: holds an empty elliptic curve point`);\r\n\r\n if (point[0] === 0x04) {\r\n\r\n if (point.length !== 1 + 2 * width)\r\n throw new CoseError(`${what}: holds an uncompressed point of ${String(point.length)} octets, where the curve '${curve.name}' needs ${String(1 + 2 * width)}`);\r\n\r\n return CoseKey.fromCoordinates(curve,\r\n point.subarray(1, 1 + width),\r\n point.subarray(1 + width));\r\n\r\n }\r\n\r\n if (point[0] === 0x02 || point[0] === 0x03) {\r\n\r\n if (point.length !== 1 + width)\r\n throw new CoseError(`${what}: holds a compressed point of ${String(point.length)} octets, where the curve '${curve.name}' needs ${String(1 + width)}`);\r\n\r\n const x = point.subarray(1);\r\n\r\n return CoseKey.fromCoordinates(curve, x, decompressY(curve, x, point[0] === 0x03));\r\n\r\n }\r\n\r\n throw new CoseError(`${what}: holds an elliptic curve point whose first octet is 0x${point[0]!.toString(16).padStart(2, '0')}, which is neither 0x04, 0x02 nor 0x03`);\r\n\r\n}\r\n\r\n\r\n/**\r\n * An ECDSA signature from a certificate, in the fixed-width form COSE uses.\r\n *\r\n * This is a real difference between the two worlds and not a formality: X.509\r\n * writes `SEQUENCE { INTEGER r, INTEGER s }`, whose length varies with the\r\n * leading zero bits of the two integers, and COSE writes `r ‖ s` padded to the\r\n * width of the group order. The same signature, two encodings, and an\r\n * implementation that hands one to the other verifies nothing.\r\n */\r\nfunction rawEcdsaSignature(der: Uint8Array, curve: CoseCurve | null, subject: string): Uint8Array {\r\n\r\n const width = curve?.orderSize ?? null;\r\n\r\n if (width === null)\r\n throw new CoseError(`The signature of the certificate '${subject}' can not be read without knowing the issuer's curve!`);\r\n\r\n const what = `The ECDSA signature of the certificate '${subject}'`;\r\n const outer = new DerReader(der, what);\r\n const sequence = contentsOf(outer.read(Tag.sequence), what);\r\n\r\n outer.expectEnd();\r\n\r\n const r = derInteger(sequence.read(Tag.integer), `${what}: r`);\r\n const s = derInteger(sequence.read(Tag.integer), `${what}: s`);\r\n\r\n sequence.expectEnd();\r\n\r\n if (r <= 0n || s <= 0n)\r\n throw new CoseError(`${what}: both halves must be positive`);\r\n\r\n const raw = new Uint8Array(2 * width);\r\n\r\n writeBigInt(r, raw, 0, width, what, 'r');\r\n writeBigInt(s, raw, width, width, what, 's');\r\n\r\n return raw;\r\n\r\n}\r\n\r\n\r\nfunction writeBigInt(value: bigint, into: Uint8Array, at: number,\r\n width: number, what: string, half: string): void {\r\n\r\n let hex = value.toString(16);\r\n\r\n if (hex.length % 2 !== 0)\r\n hex = `0${hex}`;\r\n\r\n if (hex.length / 2 > width)\r\n throw new CoseError(`${what}: ${half} is ${String(hex.length / 2)} octets, which is wider than the group order`);\r\n\r\n const offset = at + width - hex.length / 2;\r\n\r\n for (let index = 0; index < hex.length / 2; index++)\r\n into[offset + index] = Number.parseInt(hex.slice(2 * index, 2 * index + 2), 16);\r\n\r\n}\r\n\r\n\r\n/** The extensions this implementation looks at, and the identity of the rest. */\r\nfunction parseExtensions(node: Asn1Node, what: string): {\r\n basicConstraints: BasicConstraints | null;\r\n keyUsage: readonly boolean[] | null;\r\n critical: string[];\r\n} {\r\n\r\n const list = contentsOf(contentsOf(node, `${what}: the extensions`).read(Tag.sequence),\r\n `${what}: the extensions`);\r\n const critical: string[] = [];\r\n const seen = new Set<string>();\r\n\r\n let basicConstraints: BasicConstraints | null = null;\r\n let keyUsage: readonly boolean[] | null = null;\r\n\r\n while (!list.atEnd) {\r\n\r\n const extension = contentsOf(list.read(Tag.sequence), `${what}: an extension`);\r\n const oid = derObjectIdentifier(extension.read(Tag.objectIdentifier), `${what}: an extension identifier`);\r\n\r\n if (seen.has(oid))\r\n throw new CoseError(`${what}: carries the extension '${oid}' more than once, which RFC 5280 forbids`);\r\n\r\n seen.add(oid);\r\n\r\n const criticalNode = extension.peekIs(Tag.boolean) ? extension.read(Tag.boolean) : null;\r\n\r\n if (criticalNode !== null && derBoolean(criticalNode, `${what}: the criticality of '${oid}'`))\r\n critical.push(oid);\r\n\r\n const value = extension.read(Tag.octetString);\r\n\r\n extension.expectEnd();\r\n\r\n if (oid === OID_BASIC_CONSTRAINTS)\r\n basicConstraints = parseBasicConstraints(value, what);\r\n\r\n else if (oid === OID_KEY_USAGE)\r\n keyUsage = parseKeyUsage(value, what);\r\n\r\n }\r\n\r\n return { basicConstraints, keyUsage, critical };\r\n\r\n}\r\n\r\n\r\nfunction parseBasicConstraints(value: Asn1Node, what: string): BasicConstraints {\r\n\r\n const where = `${what}: the basicConstraints extension`;\r\n const outer = new DerReader(value.content, where);\r\n const sequence = contentsOf(outer.read(Tag.sequence), where);\r\n\r\n outer.expectEnd();\r\n\r\n // Both fields are DEFAULT/OPTIONAL, and DER omits a field at its default —\r\n // so `cA` absent means false, and an encoder writing FALSE explicitly is\r\n // the one in the wrong.\r\n const caNode = sequence.peekIs(Tag.boolean) ? sequence.read(Tag.boolean) : null;\r\n const pathNode = sequence.peekIs(Tag.integer) ? sequence.read(Tag.integer) : null;\r\n\r\n sequence.expectEnd();\r\n\r\n return {\r\n certificateAuthority: caNode === null ? false : derBoolean(caNode, where),\r\n pathLength: pathNode === null ? null : Number(derInteger(pathNode, where)),\r\n };\r\n\r\n}\r\n\r\n\r\nfunction parseKeyUsage(value: Asn1Node, what: string): readonly boolean[] {\r\n\r\n const where = `${what}: the keyUsage extension`;\r\n const outer = new DerReader(value.content, where);\r\n const { unusedBits, bytes } = derBitStringRaw(outer.read(Tag.bitString), where);\r\n\r\n outer.expectEnd();\r\n\r\n const bits: boolean[] = [];\r\n\r\n for (let index = 0; index < bytes.length * 8 - unusedBits; index++)\r\n bits.push((bytes[index >> 3]! & (0x80 >> (index & 7))) !== 0);\r\n\r\n return bits;\r\n\r\n}\r\n\r\n\r\n/** The COSE algorithm a certificate signature identifier corresponds to. */\r\nexport const signatureAlgorithmByOid = (oid: string): CoseAlgorithm | null =>\r\n SIGNATURE_OIDS[oid] ?? null;\r\n\r\n\r\n/** The curve a `SubjectPublicKeyInfo` identifier names. */\r\nexport const curveByOid = (oid: string): CoseCurve | null =>\r\n CURVE_OIDS[oid] ?? null;\r\n\r\n\r\n/** The object identifier of a curve, which is the inverse of {@link curveByOid}. */\r\nexport function oidOfCurve(curve: CoseCurve): string | null {\r\n\r\n for (const [oid, each] of Object.entries(CURVE_OIDS)) {\r\n if (each.id === curve.id)\r\n return oid;\r\n }\r\n\r\n return null;\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * The X.509 header parameters of COSE [RFC 9360].\r\n *\r\n * Two of them are implemented here: `x5chain` (label 33), which carries a\r\n * chain of certificates, and `x5t` (label 34), which carries the hash of one.\r\n * `x5bag` and `x5u` are not — a bag is an unordered heap with no path to\r\n * follow, and a URI is a fetch, which a signature library has no business\r\n * performing.\r\n *\r\n * The distinction that matters most is between the two implemented ones. A\r\n * chain is evidence; a thumbprint is a *name*. `x5t` says which certificate\r\n * the sender meant, so that a recipient who already holds it can find it — it\r\n * is never a reason to trust one, and a recipient who does not have the\r\n * certificate learns nothing from its hash.\r\n */\r\n\r\nimport { algorithmById, CoseAlgorithms } from './algorithm.ts';\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport { cbor } from './cbor.ts';\r\nimport type { CborValue } from './cbor.ts';\r\nimport { CoseError, notVerified, VERIFIED } from './errors.ts';\r\nimport type { Verification } from './errors.ts';\r\nimport type { CoseKey } from './key.ts';\r\nimport { KeyUsage, X509Certificate } from './x509.ts';\r\n\r\n\r\n/** How a chain is to be validated. */\r\nexport interface ChainValidationOptions {\r\n\r\n /**\r\n * The instant to check the validity periods at, now by default.\r\n *\r\n * Worth passing whenever the answer has to be reproducible — a conformance\r\n * vector, an archived message, a signature being re-checked years later —\r\n * because \"now\" makes the same input give different answers on different\r\n * days.\r\n */\r\n readonly at?: Date;\r\n\r\n}\r\n\r\n\r\n// ------------------------------------------------------------------ chain ---\r\n\r\n/**\r\n * A `COSE_X509` [RFC 9360, Section 2] — a chain of X.509 certificates.\r\n *\r\n * ```\r\n * COSE_X509 = bstr / [ 2*certs: bstr ]\r\n * ```\r\n *\r\n * A single certificate is a bare byte string; two or more form an array. The\r\n * order is end-entity first, then whoever signed it, and so on. The trust\r\n * anchor need not be present — the recipient is expected to have it already,\r\n * which is what makes it an anchor.\r\n *\r\n * A chain proves nothing on its own. It becomes an answer only once\r\n * {@link validate} has walked it to an anchor the recipient configured, and\r\n * once the key of its end-entity certificate turns out to be the key that\r\n * verified the signature — which is\r\n * {@link CoseSign1.verifyWithCertificateChain}'s half of the job.\r\n */\r\nexport class CoseCertificateChain {\r\n\r\n /** The certificates, end-entity first. */\r\n public readonly certificates: readonly X509Certificate[];\r\n\r\n\r\n public constructor(certificates: readonly X509Certificate[]) {\r\n\r\n if (certificates.length === 0)\r\n throw new CoseError('A certificate chain must hold at least one certificate!');\r\n\r\n this.certificates = [...certificates];\r\n\r\n }\r\n\r\n\r\n /** The certificate holding the key that is expected to have signed. */\r\n public get endEntity(): X509Certificate {\r\n return this.certificates[0]!;\r\n }\r\n\r\n\r\n /** The public key of the end-entity certificate. */\r\n public publicKey(): CoseKey {\r\n return this.endEntity.publicKey;\r\n }\r\n\r\n\r\n // ------------------------------------------------------------- parsing\r\n\r\n /** Read a `COSE_X509` from its CBOR form. */\r\n public static fromCbor(value: CborValue): CoseCertificateChain {\r\n\r\n const encoded: Uint8Array[] = [];\r\n\r\n if (value.type === 'bytes')\r\n encoded.push(value.value);\r\n\r\n else if (value.type === 'array') {\r\n\r\n // RFC 9360 spells the array as \"2*certs\": a chain of exactly one\r\n // certificate is a bare byte string, never an array of one.\r\n if (value.items.length < 2)\r\n throw new CoseError('A COSE_X509 of fewer than two certificates must be a bare byte string, not an array!');\r\n\r\n for (const item of value.items) {\r\n\r\n if (item.type !== 'bytes')\r\n throw new CoseError('Every certificate of a COSE_X509 must be a byte string!');\r\n\r\n encoded.push(item.value);\r\n\r\n }\r\n\r\n }\r\n\r\n else\r\n throw new CoseError(`A COSE_X509 must be a byte string or an array of them, but was a CBOR ${value.type}!`);\r\n\r\n return new CoseCertificateChain(encoded.map((each, index) => {\r\n\r\n try {\r\n return X509Certificate.parse(each);\r\n }\r\n catch (exception) {\r\n throw new CoseError(`The certificate at position ${String(index)} of the COSE_X509 could not be read: ${exception instanceof Error ? exception.message : String(exception)}`,\r\n { cause: exception });\r\n }\r\n\r\n }));\r\n\r\n }\r\n\r\n\r\n /** The CBOR form: a bare byte string for one certificate, an array for several. */\r\n public toCbor(): CborValue {\r\n\r\n return this.certificates.length === 1\r\n ? cbor.bytes(this.certificates[0]!.encoded)\r\n : cbor.array(this.certificates.map(each => cbor.bytes(each.encoded)));\r\n\r\n }\r\n\r\n\r\n // ---------------------------------------------------------- validation\r\n\r\n /**\r\n * Walk this chain to one of the given trust anchors.\r\n *\r\n * Every certificate within its validity period, every certificate signed\r\n * by the next one, every issuing certificate actually allowed to issue,\r\n * the last one either an anchor or issued by one, and the end-entity\r\n * certificate allowed to sign.\r\n *\r\n * This answers \"does this chain lead somewhere I trust\". It does *not*\r\n * answer whether the key of the end-entity certificate is the key that\r\n * signed the message — without that binding a perfectly valid chain says\r\n * nothing about the message it travelled with.\r\n *\r\n * Not checked, and the same list as Styx so that the two agree about what\r\n * a pass means: revocation, name constraints, certificate policies, and\r\n * path length beyond the CA flag.\r\n */\r\n public validate(trustAnchors: readonly X509Certificate[],\r\n options: ChainValidationOptions = {}): Verification {\r\n\r\n const at = options.at ?? new Date();\r\n\r\n if (trustAnchors.length === 0)\r\n return notVerified('A certificate chain can not be validated without at least one trust anchor!');\r\n\r\n for (const certificate of this.certificates) {\r\n\r\n const valid = certificate.isValidAt(at);\r\n\r\n if (!valid.verified)\r\n return valid;\r\n\r\n }\r\n\r\n for (let index = 0; index < this.certificates.length - 1; index++) {\r\n\r\n const issuer = this.certificates[index + 1]!;\r\n const issued = this.certificates[index]!.verifySignedBy(issuer);\r\n\r\n if (!issued.verified)\r\n return issued;\r\n\r\n const allowed = mayIssue(issuer);\r\n\r\n if (!allowed.verified)\r\n return allowed;\r\n\r\n }\r\n\r\n const last = this.certificates[this.certificates.length - 1]!;\r\n\r\n // Either the chain ends *at* an anchor, or it ends at something an\r\n // anchor issued — the anchor itself need not travel.\r\n if (!trustAnchors.some(anchor => anchor.equals(last))) {\r\n\r\n const issuer = trustAnchors.find(anchor => last.issuer.equivalentTo(anchor.subject));\r\n\r\n if (issuer === undefined)\r\n return notVerified(`The certificate chain ends at '${last.subject.toString()}', which is neither a trust anchor nor issued by one!`);\r\n\r\n for (const check of [issuer.isValidAt(at), mayIssue(issuer), last.verifySignedBy(issuer)]) {\r\n\r\n if (!check.verified)\r\n return check;\r\n\r\n }\r\n\r\n }\r\n\r\n if (!this.endEntity.allows(KeyUsage.digitalSignature))\r\n return notVerified(`The end-entity certificate '${this.endEntity.subject.toString()}' is not allowed to create digital signatures!`);\r\n\r\n return VERIFIED;\r\n\r\n }\r\n\r\n\r\n public toString(): string {\r\n return this.certificates.map(each => each.subject.toString()).join(' <- ');\r\n }\r\n\r\n}\r\n\r\n\r\n/** Whether a certificate was allowed to issue the one below it. */\r\nfunction mayIssue(certificate: X509Certificate): Verification {\r\n\r\n if (!certificate.isCertificateAuthority)\r\n return notVerified(`The certificate '${certificate.subject.toString()}' issued another one although it is not a certification authority!`);\r\n\r\n if (!certificate.allows(KeyUsage.keyCertSign))\r\n return notVerified(`The certificate '${certificate.subject.toString()}' issued another one although it is not allowed to sign certificates!`);\r\n\r\n return VERIFIED;\r\n\r\n}\r\n\r\n\r\n// ------------------------------------------------------------- thumbprint ---\r\n\r\n/**\r\n * A `COSE_CertHash` [RFC 9360, Section 2] — the hash of a DER encoded\r\n * certificate, as `x5t` carries it.\r\n *\r\n * ```\r\n * COSE_CertHash = [ hashAlg: (int / tstr), hashValue: bstr ]\r\n * ```\r\n */\r\nexport class CoseCertificateHash {\r\n\r\n /** The hash algorithm the thumbprint was computed with. */\r\n public readonly algorithm: CoseAlgorithm;\r\n\r\n /** The hash of the certificate's DER encoding. */\r\n public readonly value: Uint8Array;\r\n\r\n\r\n public constructor(algorithm: CoseAlgorithm, value: Uint8Array) {\r\n this.algorithm = algorithm;\r\n this.value = value;\r\n }\r\n\r\n\r\n /** Compute the thumbprint of a certificate, with SHA-256 unless told otherwise. */\r\n public static from(certificate: X509Certificate,\r\n algorithm: CoseAlgorithm = CoseAlgorithms.SHA256): CoseCertificateHash {\r\n\r\n if (algorithm.hash === null)\r\n throw new CoseError(`The COSE algorithm '${algorithm.name}' is not a hash algorithm!`);\r\n\r\n return new CoseCertificateHash(algorithm, certificate.thumbprint(algorithm.hash));\r\n\r\n }\r\n\r\n\r\n /** Read a `COSE_CertHash` from its CBOR form. */\r\n public static fromCbor(value: CborValue): CoseCertificateHash {\r\n\r\n if (value.type !== 'array')\r\n throw new CoseError(`A COSE_CertHash must be a CBOR array, but was a CBOR ${value.type}!`);\r\n\r\n if (value.items.length !== 2)\r\n throw new CoseError(`A COSE_CertHash must hold exactly two elements, but held ${String(value.items.length)}!`);\r\n\r\n const [algorithmValue, hashValue] = value.items as [CborValue, CborValue];\r\n\r\n if (hashValue.type !== 'bytes')\r\n throw new CoseError('The hash value of a COSE_CertHash must be a byte string!');\r\n\r\n if (algorithmValue.type !== 'int')\r\n throw new CoseError('The hash algorithm of a COSE_CertHash must be an integer, as no name is registered for one!');\r\n\r\n const algorithm = algorithmById(Number(algorithmValue.value));\r\n\r\n if (algorithm === null)\r\n throw new CoseError(`The COSE algorithm ${String(algorithmValue.value)} of the COSE_CertHash is not registered!`);\r\n\r\n if (algorithm.hash === null)\r\n throw new CoseError(`The COSE algorithm '${algorithm.name}' of the COSE_CertHash is not a hash algorithm!`);\r\n\r\n return new CoseCertificateHash(algorithm, hashValue.value);\r\n\r\n }\r\n\r\n\r\n /** The CBOR form. */\r\n public toCbor(): CborValue {\r\n return cbor.array([cbor.int(BigInt(this.algorithm.id)), cbor.bytes(this.value)]);\r\n }\r\n\r\n\r\n /**\r\n * Whether this thumbprint names the given certificate.\r\n *\r\n * A thumbprint that names a *different* certificate than the one that\r\n * travelled is not a detail to shrug at: the message states which\r\n * certificate it means, and the chain offers another. One of the two is\r\n * wrong and there is no way to tell which.\r\n */\r\n public matches(certificate: X509Certificate): Verification {\r\n\r\n if (this.algorithm.hash === null)\r\n return notVerified(`The COSE algorithm '${this.algorithm.name}' of the certificate thumbprint is not a hash algorithm!`);\r\n\r\n const computed = certificate.thumbprint(this.algorithm.hash);\r\n\r\n if (computed.length !== this.value.length ||\r\n !computed.every((each, index) => each === this.value[index]))\r\n return notVerified(`The certificate thumbprint of this message does not name the certificate '${certificate.subject.toString()}' that travelled with it!`);\r\n\r\n return VERIFIED;\r\n\r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * A COSE_Sign1 message [RFC 9052, Section 4.2]: a payload signed by a single\r\n * signer, tagged with CBOR tag 18.\r\n *\r\n * <code>\r\n * COSE_Sign1 = [\r\n * protected : bstr .cbor header_map, ; covered by the signature\r\n * unprotected : header_map, ; NOT covered by the signature\r\n * payload : bstr / nil, ; nil = detached\r\n * signature : bstr\r\n * ]\r\n * </code>\r\n *\r\n * What is actually signed is never the message, but the Sig_structure\r\n * `[\"Signature1\", protected, external_aad, payload]` [RFC 9052, Section 4.4].\r\n * The CBOR tag is therefore *not* covered by the signature, and the same\r\n * message with and without tag 18 carries the very same signature bytes.\r\n *\r\n * The serialized protected bucket is kept verbatim, because a re-serialization\r\n * differing in a single byte — a non-preferred integer head, a different map\r\n * order — would invalidate every signature made over the original bytes.\r\n */\r\n\r\nimport { signWith, verifyWith } from './algorithm.ts';\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport { bytesEqual, cbor, decode, encode,\r\n NO_BYTES } from './cbor.ts';\r\nimport type { CborValue } from './cbor.ts';\r\nimport { CoseError, notVerified, VERIFIED } from './errors.ts';\r\nimport type { NotVerified, Verification } from './errors.ts';\r\nimport { CoseHeaders,\r\n verifyCriticalHeaderParameters } from './headers.ts';\r\nimport type { CoseKey } from './key.ts';\r\nimport { HeaderLabel, label } from './labels.ts';\r\nimport { canonicalizePayload } from './payload.ts';\r\nimport { resolveAlgorithm, resolvePayload } from './resolve.ts';\r\nimport { CoseSignature } from './signature.ts';\r\nimport { CoseCertificateChain,\r\n CoseCertificateHash } from './x5chain.ts';\r\nimport type { X509Certificate } from './x509.ts';\r\n\r\n\r\n/** The CBOR tag of a COSE_Sign1 message. */\r\nexport const COSE_SIGN1_TAG = 18;\r\n\r\n/** The context string of a COSE_Sign1 signature [RFC 9052, Section 4.4]. */\r\nexport const SIGNATURE_CONTEXT = 'Signature1';\r\n\r\n/**\r\n * The context string of a countersignature that also covers the signature it\r\n * countersigns [RFC 9338, Section 3.3].\r\n */\r\nexport const COUNTERSIGNATURE_CONTEXT = 'CounterSignatureV2';\r\n\r\n\r\n/** What a signer may choose beyond the payload and the key. */\r\nexport interface Sign1Options {\r\n\r\n /** A key identifier for the unprotected bucket, defaulting to the key's own. */\r\n readonly keyIdentifier?: Uint8Array | null;\r\n\r\n /** Data signed along with the payload without travelling in the message. */\r\n readonly externalAad?: Uint8Array | null;\r\n\r\n /** Whether to omit the payload from the message. */\r\n readonly detachPayload?: boolean;\r\n\r\n /** Whether to wrap the message within CBOR tag 18. Defaults to true. */\r\n readonly tagged?: boolean;\r\n\r\n /**\r\n * Whether to rewrite a CBOR payload in the deterministic encoding of\r\n * RFC 8949 Section 4.2.1 before signing it, so that a receiver who parses\r\n * and re-serializes the record arrives at the very bytes the signature\r\n * covers. Defaults to true. A payload that is not CBOR is signed as it is.\r\n */\r\n readonly canonicalizePayload?: boolean;\r\n\r\n}\r\n\r\n\r\n/** What a verifier may have to supply. */\r\nexport interface VerifyOptions {\r\n\r\n /** The data that was signed along with the payload. */\r\n readonly externalAad?: Uint8Array | null;\r\n\r\n /** The payload, when the message carries a detached one. */\r\n readonly detachedPayload?: Uint8Array | null;\r\n\r\n /**\r\n * The algorithm the caller expects, required whenever the message states\r\n * its algorithm within the unprotected bucket only.\r\n */\r\n readonly expectedAlgorithm?: CoseAlgorithm | null;\r\n\r\n /**\r\n * Header parameters the caller processes itself, and which a `crit`\r\n * header parameter may therefore demand.\r\n */\r\n readonly alsoUnderstood?: readonly CborValue[];\r\n\r\n}\r\n\r\n\r\n/** What a verifier working from a certificate chain may supply beyond that. */\r\nexport interface CertificateChainVerifyOptions extends VerifyOptions {\r\n\r\n /**\r\n * The instant to check the certificates' validity periods at, now by\r\n * default. Worth passing whenever the answer has to be reproducible: an\r\n * archived message re-checked years later is checked against the\r\n * certificates of its own time, not of today.\r\n */\r\n readonly at?: Date;\r\n\r\n}\r\n\r\n\r\n/**\r\n * The outcome of verifying against a certificate chain.\r\n *\r\n * A success names the certificate whose key verified, because \"it verified\" is\r\n * only half of what the caller asked: the other half is *who*, and a chain\r\n * exists precisely to answer that.\r\n */\r\nexport type CertificateChainVerification =\r\n | { readonly verified: true; readonly signer: X509Certificate }\r\n | NotVerified;\r\n\r\n\r\nexport class CoseSign1 {\r\n\r\n /**\r\n * The serialized protected bucket, exactly as signed and as received: a\r\n * zero-length byte string when there are no protected header parameters.\r\n */\r\n public readonly protectedHeaderBytes: Uint8Array;\r\n\r\n /** The protected header parameters, which the signature covers. */\r\n public readonly protectedHeader: CoseHeaders;\r\n\r\n /**\r\n * The unprotected header parameters, which the signature does not cover\r\n * and which therefore must not be trusted after a successful verification.\r\n */\r\n public readonly unprotectedHeader: CoseHeaders;\r\n\r\n /** The signed payload, or null when it is detached. */\r\n public readonly payload: Uint8Array | null;\r\n\r\n /** The signature: `r ‖ s`, each half zero-padded, never DER. */\r\n public readonly signature: Uint8Array;\r\n\r\n /**\r\n * Whether this message is wrapped within CBOR tag 18. The tag is not\r\n * covered by the signature, but it is preserved so that a parsed message\r\n * re-encodes to the very same bytes.\r\n */\r\n public readonly isTagged: boolean;\r\n\r\n\r\n public constructor(protectedHeaderBytes: Uint8Array,\r\n unprotectedHeader: CoseHeaders | null,\r\n payload: Uint8Array | null,\r\n signature: Uint8Array,\r\n isTagged = true) {\r\n\r\n this.protectedHeaderBytes = protectedHeaderBytes;\r\n this.protectedHeader = CoseHeaders.parseProtected(protectedHeaderBytes);\r\n this.unprotectedHeader = unprotectedHeader ?? CoseHeaders.empty;\r\n this.payload = payload;\r\n this.signature = signature;\r\n this.isTagged = isTagged;\r\n\r\n }\r\n\r\n\r\n /** Whether the payload is detached. */\r\n public get isDetached(): boolean {\r\n return this.payload === null;\r\n }\r\n\r\n /**\r\n * The signature algorithm, taken from the protected bucket and only\r\n * otherwise from the unprotected one.\r\n */\r\n public get algorithm(): CoseAlgorithm | null {\r\n return this.protectedHeader.algorithm ?? this.unprotectedHeader.algorithm;\r\n }\r\n\r\n /** The key identifier, protected bucket first. */\r\n public get keyIdentifier(): Uint8Array | null {\r\n return this.protectedHeader.keyIdentifier ?? this.unprotectedHeader.keyIdentifier;\r\n }\r\n\r\n\r\n // ---------------------------------------------------------------- signing\r\n\r\n /**\r\n * The encoded Sig_structure of a COSE_Sign1 message\r\n * [RFC 9052, Section 4.4], which is the byte string an ECDSA signer\r\n * actually signs:\r\n *\r\n * <code>\r\n * Sig_structure = [\r\n * context : \"Signature1\",\r\n * protected : empty_or_serialized_map,\r\n * external_aad : bstr,\r\n * payload : bstr\r\n * ]\r\n * </code>\r\n *\r\n * This is public on purpose. Whenever the signing key does not live in\r\n * this process — a meter, a smart card, a hardware security module — this\r\n * is the input to hand over.\r\n */\r\n public static toBeSigned(protectedHeaderBytes: Uint8Array,\r\n payload: Uint8Array,\r\n externalAad: Uint8Array | null = null): Uint8Array {\r\n\r\n return encode(cbor.array([\r\n cbor.text(SIGNATURE_CONTEXT),\r\n cbor.bytes(protectedHeaderBytes),\r\n cbor.bytes(externalAad ?? NO_BYTES),\r\n cbor.bytes(payload),\r\n ]));\r\n\r\n }\r\n\r\n\r\n /** The encoded Sig_structure of this message. */\r\n public toBeSigned(options: { externalAad?: Uint8Array | null;\r\n detachedPayload?: Uint8Array | null } = {}): Uint8Array {\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Sign1 message');\r\n\r\n if (!payload.ok)\r\n throw new CoseError(payload.reason);\r\n\r\n return CoseSign1.toBeSigned(this.protectedHeaderBytes,\r\n payload.value,\r\n options.externalAad ?? null);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Sign a payload, placing the algorithm within the protected bucket and\r\n * the key identifier within the unprotected one — the layout of the\r\n * examples of RFC 9052 and of virtually every deployed COSE message.\r\n */\r\n public static sign(payload: Uint8Array,\r\n key: CoseKey,\r\n options: Sign1Options = {}): CoseSign1 {\r\n\r\n const algorithm = key.algorithm;\r\n\r\n if (algorithm === null)\r\n throw new CoseError('The COSE key does not name the signature algorithm to use!');\r\n\r\n const keyIdentifier = options.keyIdentifier === undefined\r\n ? key.keyIdentifier\r\n : options.keyIdentifier;\r\n\r\n return CoseSign1.signWithHeaders(payload,\r\n key,\r\n CoseHeaders.create(algorithm),\r\n keyIdentifier !== null\r\n ? CoseHeaders.create(null, keyIdentifier)\r\n : CoseHeaders.empty,\r\n options);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Sign a payload with the algorithm taken from the application context\r\n * rather than from the message: the protected bucket stays empty and only\r\n * the key identifier travels.\r\n *\r\n * This is the leanest signed COSE message there is, and for a protocol\r\n * that already agrees on its algorithm it is also the safest arrangement:\r\n * an algorithm that is not in the message cannot be tampered with on the\r\n * way, whereas one within the unprotected bucket can. The price is that\r\n * agility becomes a property of the profile rather than of the message.\r\n */\r\n public static signWithApplicationAlgorithm(payload: Uint8Array,\r\n key: CoseKey,\r\n options: Sign1Options = {}): CoseSign1 {\r\n\r\n const algorithm = key.algorithm;\r\n\r\n if (algorithm === null)\r\n throw new CoseError('The COSE key does not name the signature algorithm to use!');\r\n\r\n const keyIdentifier = options.keyIdentifier === undefined\r\n ? key.keyIdentifier\r\n : options.keyIdentifier;\r\n\r\n return CoseSign1.signWithHeaders(payload,\r\n key,\r\n CoseHeaders.empty,\r\n keyIdentifier !== null\r\n ? CoseHeaders.create(null, keyIdentifier)\r\n : CoseHeaders.empty,\r\n options,\r\n algorithm);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Sign a payload with full control over both header buckets.\r\n *\r\n * The signature algorithm is taken from the protected bucket, because an\r\n * algorithm that is not covered by the signature could be changed by\r\n * anyone on the way.\r\n */\r\n public static signWithHeaders(payload: Uint8Array,\r\n key: CoseKey,\r\n protectedHeader: CoseHeaders,\r\n unprotectedHeader: CoseHeaders | null = null,\r\n options: Sign1Options = {},\r\n applicationAlgorithm: CoseAlgorithm | null = null): CoseSign1 {\r\n\r\n const stated = protectedHeader.algorithm;\r\n\r\n if (applicationAlgorithm !== null && stated !== null && stated.id !== applicationAlgorithm.id)\r\n throw new CoseError(`The protected header bucket names the algorithm '${stated.name}', but the application context names '${applicationAlgorithm.name}'!`);\r\n\r\n const algorithm = stated ?? applicationAlgorithm;\r\n\r\n if (algorithm === null)\r\n throw new CoseError('Neither the protected header bucket nor the application context names the signature algorithm!');\r\n\r\n const protectedBytes = protectedHeader.toProtectedBytes();\r\n\r\n const signed = options.canonicalizePayload === false\r\n ? payload\r\n : canonicalizePayload(payload);\r\n\r\n // A detached payload is the caller's to transmit, so it is the\r\n // caller's bytes a verifier will be handed. Quietly signing a\r\n // different spelling of them would produce a message that can never\r\n // verify, and the only hint would be a failed check somewhere else.\r\n if (options.detachPayload === true && !bytesEqual(signed, payload))\r\n throw new CoseError('The payload of this COSE_Sign1 message is detached, so canonicalizing it here would sign bytes that nobody holds: canonicalize the payload yourself (canonicalizePayload), sign and transmit those, or pass canonicalizePayload: false to sign the payload exactly as it is!');\r\n\r\n const signature = signWith(algorithm,\r\n key.curve,\r\n CoseSign1.toBeSigned(protectedBytes, signed, options.externalAad ?? null),\r\n key.privateKeyBytes());\r\n\r\n return new CoseSign1(protectedBytes,\r\n unprotectedHeader,\r\n options.detachPayload === true ? null : signed,\r\n signature,\r\n options.tagged ?? true);\r\n\r\n }\r\n\r\n\r\n // ----------------------------------------------------------- verification\r\n\r\n /**\r\n * Verify the signature of this message.\r\n *\r\n * A failed verification is not an exception — it is the expected outcome\r\n * of checking untrusted data — so the reason travels in the result.\r\n */\r\n public verify(key: CoseKey, options: VerifyOptions = {}): Verification {\r\n\r\n const critical = verifyCriticalHeaderParameters(this.protectedHeader,\r\n this.unprotectedHeader,\r\n options.alsoUnderstood ?? []);\r\n\r\n if (!critical.verified)\r\n return critical;\r\n\r\n const algorithm = resolveAlgorithm(this.protectedHeader,\r\n this.unprotectedHeader,\r\n options.expectedAlgorithm ?? key.algorithm,\r\n 'This COSE_Sign1 message');\r\n\r\n if (!algorithm.ok)\r\n return notVerified(algorithm.reason);\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Sign1 message');\r\n\r\n if (!payload.ok)\r\n return notVerified(payload.reason);\r\n\r\n return verifySignature(algorithm.value,\r\n key,\r\n CoseSign1.toBeSigned(this.protectedHeaderBytes,\r\n payload.value,\r\n options.externalAad ?? null),\r\n this.signature);\r\n\r\n }\r\n\r\n\r\n // -------------------------------------------------- X.509 [RFC 9360]\r\n\r\n /**\r\n * The certificate chain of this message, from either header bucket.\r\n *\r\n * A chain that travels in a message is untrusted input, and reading one\r\n * says nothing at all about it — {@link verifyWithCertificateChain} has to\r\n * walk it to an anchor first. Throws when the parameter is present but is\r\n * not a `COSE_X509`, rather than pretending there is none.\r\n */\r\n public get certificateChain(): CoseCertificateChain | null {\r\n\r\n const value = this.protectedHeader.get(label(HeaderLabel.x5Chain)) ??\r\n this.unprotectedHeader.get(label(HeaderLabel.x5Chain));\r\n\r\n if (value === null)\r\n return null;\r\n\r\n return CoseCertificateChain.fromCbor(value);\r\n\r\n }\r\n\r\n\r\n /**\r\n * The certificate thumbprint of this message, from either header bucket.\r\n *\r\n * Throws when the parameter is present but is not a `COSE_CertHash`.\r\n */\r\n public get certificateThumbprint(): CoseCertificateHash | null {\r\n\r\n const value = this.protectedHeader.get(label(HeaderLabel.x5T)) ??\r\n this.unprotectedHeader.get(label(HeaderLabel.x5T));\r\n\r\n if (value === null)\r\n return null;\r\n\r\n return CoseCertificateHash.fromCbor(value);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Verify this message against a certificate chain rather than against a\r\n * public key somebody handed over: the chain travels within the message,\r\n * is walked to one of the given trust anchors, and the key of its\r\n * end-entity certificate is then the key the signature has to verify with.\r\n *\r\n * That last step is what turns a chain into an answer. A chain that\r\n * validates beautifully says nothing whatsoever about the message it\r\n * arrived with unless the key it ends in is the key that signed, so the\r\n * two are never checked apart from one another here.\r\n *\r\n * The X.509 header parameters become understood *by this call* rather than\r\n * by the library, which is why a `crit` demanding `x5chain` is accepted\r\n * here and refused by {@link verify}: whoever verifies with a bare public\r\n * key has not looked at any certificate and must not claim otherwise.\r\n */\r\n public verifyWithCertificateChain(trustAnchors: readonly X509Certificate[],\r\n options: CertificateChainVerifyOptions = {}): CertificateChainVerification {\r\n\r\n const understood = [...(options.alsoUnderstood ?? []),\r\n label(HeaderLabel.x5Chain),\r\n label(HeaderLabel.x5T)];\r\n\r\n const critical = verifyCriticalHeaderParameters(this.protectedHeader,\r\n this.unprotectedHeader,\r\n understood);\r\n\r\n if (!critical.verified)\r\n return critical;\r\n\r\n let chain: CoseCertificateChain | null;\r\n let thumbprint: CoseCertificateHash | null;\r\n\r\n try {\r\n chain = this.certificateChain;\r\n thumbprint = this.certificateThumbprint;\r\n }\r\n catch (exception) {\r\n return notVerified(exception instanceof Error ? exception.message : String(exception));\r\n }\r\n\r\n if (chain === null)\r\n return notVerified('This COSE_Sign1 message carries no certificate chain!');\r\n\r\n if (thumbprint !== null) {\r\n\r\n const names = thumbprint.matches(chain.endEntity);\r\n\r\n if (!names.verified)\r\n return names;\r\n\r\n }\r\n\r\n const validated = chain.validate(trustAnchors, { at: options.at });\r\n\r\n if (!validated.verified)\r\n return validated;\r\n\r\n // Whether the certified key is one this algorithm can verify with is\r\n // the algorithm's question and not this one's: an EdDSA or an ML-DSA\r\n // certificate is as good a binding as an elliptic curve one.\r\n const signed = this.verify(chain.publicKey(),\r\n { ...options, alsoUnderstood: understood });\r\n\r\n if (!signed.verified)\r\n return signed;\r\n\r\n return { verified: true, signer: chain.endEntity };\r\n\r\n }\r\n\r\n\r\n // ------------------------------------------------------- countersignatures\r\n\r\n /**\r\n * The countersignatures of this message [RFC 9338], which live in the\r\n * unprotected bucket under label 11.\r\n *\r\n * A message carrying one holds it bare; a message carrying several holds\r\n * an array of them. The two shapes are told apart by the kind of the first\r\n * element, because a bare countersignature starts with its protected\r\n * bucket, a byte string, whereas an array of them starts with an array.\r\n */\r\n public get countersignatures(): readonly CoseSignature[] {\r\n\r\n const value = this.unprotectedHeader.get(label(HeaderLabel.counterSignatureV2));\r\n\r\n if (value === null)\r\n return [];\r\n\r\n if (value.type !== 'array')\r\n throw new CoseError('The countersignature header parameter must be a COSE_Countersignature or an array of them!');\r\n\r\n if (value.items.length > 0 && value.items[0]!.type === 'array')\r\n return value.items.map(each => CoseSignature.parse(each));\r\n\r\n return [CoseSignature.parse(value)];\r\n\r\n }\r\n\r\n\r\n /**\r\n * The encoded Countersign_structure [RFC 9338, Section 3.3].\r\n *\r\n * Six elements rather than four, and the difference is not cosmetic. It\r\n * names the body's protected bucket *and* the countersigner's, and its\r\n * last element carries the signature being countersigned — which is what\r\n * makes this \"I vouch for that signature\" rather than \"I signed the same\r\n * thing\". The countersignature of RFC 8152 covered the payload but not the\r\n * signature, so it never actually attested to having seen it.\r\n *\r\n * `other_fields` is an array holding the one signature, not a bare byte\r\n * string.\r\n */\r\n public static toBeCountersigned(bodyProtectedHeaderBytes: Uint8Array,\r\n countersignatureProtectedHeaderBytes: Uint8Array,\r\n payload: Uint8Array,\r\n signature: Uint8Array,\r\n externalAad: Uint8Array | null = null): Uint8Array {\r\n\r\n return encode(cbor.array([\r\n cbor.text(COUNTERSIGNATURE_CONTEXT),\r\n cbor.bytes(bodyProtectedHeaderBytes),\r\n cbor.bytes(countersignatureProtectedHeaderBytes),\r\n cbor.bytes(externalAad ?? NO_BYTES),\r\n cbor.bytes(payload),\r\n cbor.array([cbor.bytes(signature)]),\r\n ]));\r\n\r\n }\r\n\r\n\r\n /** The encoded Countersign_structure of one countersignature of this message. */\r\n public toBeCountersigned(countersignature: CoseSignature,\r\n options: { externalAad?: Uint8Array | null;\r\n detachedPayload?: Uint8Array | null } = {}): Uint8Array {\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Sign1 message');\r\n\r\n if (!payload.ok)\r\n throw new CoseError(payload.reason);\r\n\r\n return CoseSign1.toBeCountersigned(this.protectedHeaderBytes,\r\n countersignature.protectedHeaderBytes,\r\n payload.value,\r\n this.signature,\r\n options.externalAad ?? null);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Return a copy of this message with one more countersignature.\r\n *\r\n * Countersignatures live in the unprotected bucket, which no signature\r\n * covers, so this leaves the body signature, the protected bucket and the\r\n * payload byte-identical: the message stays valid for everybody, including\r\n * readers that ignore label 11 entirely.\r\n */\r\n public addCountersignature(key: CoseKey,\r\n options: Sign1Options & {\r\n detachedPayload?: Uint8Array | null } = {}): CoseSign1 {\r\n\r\n const algorithm = key.algorithm;\r\n\r\n if (algorithm === null)\r\n throw new CoseError('The COSE key does not name the signature algorithm to use!');\r\n\r\n const keyIdentifier = options.keyIdentifier === undefined\r\n ? key.keyIdentifier\r\n : options.keyIdentifier;\r\n\r\n const protectedBytes = CoseHeaders.create(algorithm).toProtectedBytes();\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Sign1 message');\r\n\r\n if (!payload.ok)\r\n throw new CoseError(payload.reason);\r\n\r\n const signature = signWith(algorithm,\r\n key.curve,\r\n CoseSign1.toBeCountersigned(this.protectedHeaderBytes,\r\n protectedBytes,\r\n payload.value,\r\n this.signature,\r\n options.externalAad ?? null),\r\n key.privateKeyBytes());\r\n\r\n const added = new CoseSignature(protectedBytes,\r\n keyIdentifier !== null\r\n ? CoseHeaders.create(null, keyIdentifier)\r\n : CoseHeaders.empty,\r\n signature);\r\n\r\n const all = [...this.countersignatures, added];\r\n\r\n return new CoseSign1(this.protectedHeaderBytes,\r\n this.unprotectedHeader.set(\r\n label(HeaderLabel.counterSignatureV2),\r\n all.length === 1\r\n ? all[0]!.toCbor()\r\n : cbor.array(all.map(each => each.toCbor()))),\r\n this.payload,\r\n this.signature,\r\n this.isTagged);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Verify one countersignature of this message.\r\n *\r\n * This says nothing about whether the body signature itself is valid —\r\n * that is a separate question with a separate key, and answering both at\r\n * once would hide which of the two failed.\r\n */\r\n public verifyCountersignature(countersignature: CoseSignature,\r\n key: CoseKey,\r\n options: VerifyOptions = {}): Verification {\r\n\r\n const critical = verifyCriticalHeaderParameters(countersignature.protectedHeader,\r\n countersignature.unprotectedHeader,\r\n options.alsoUnderstood ?? []);\r\n\r\n if (!critical.verified)\r\n return critical;\r\n\r\n const algorithm = resolveAlgorithm(countersignature.protectedHeader,\r\n countersignature.unprotectedHeader,\r\n options.expectedAlgorithm ?? key.algorithm,\r\n 'This countersignature');\r\n\r\n if (!algorithm.ok)\r\n return notVerified(algorithm.reason);\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Sign1 message');\r\n\r\n if (!payload.ok)\r\n return notVerified(payload.reason);\r\n\r\n return verifySignature(algorithm.value,\r\n key,\r\n CoseSign1.toBeCountersigned(this.protectedHeaderBytes,\r\n countersignature.protectedHeaderBytes,\r\n payload.value,\r\n this.signature,\r\n options.externalAad ?? null),\r\n countersignature.signature);\r\n\r\n }\r\n\r\n\r\n // ------------------------------------------------------ reading & writing\r\n\r\n /**\r\n * Parse a COSE_Sign1 message.\r\n *\r\n * Both the tagged and the untagged form are accepted; which one it was is\r\n * remembered, as the CBOR tag is not covered by the signature but is part\r\n * of the bytes on the wire.\r\n */\r\n public static parse(input: Uint8Array | CborValue): CoseSign1 {\r\n\r\n const value = input instanceof Uint8Array ? decode(input) : input;\r\n\r\n let isTagged = false;\r\n let message = value;\r\n\r\n if (message.type === 'tag') {\r\n\r\n if (message.tag !== BigInt(COSE_SIGN1_TAG))\r\n throw new CoseError(`A COSE_Sign1 message must be tagged with CBOR tag ${String(COSE_SIGN1_TAG)}, but was tagged with CBOR tag ${String(message.tag)}!`);\r\n\r\n isTagged = true;\r\n message = message.value;\r\n\r\n }\r\n\r\n if (message.type !== 'array')\r\n throw new CoseError(`A COSE_Sign1 message must be a CBOR array, but was a CBOR ${message.type}!`);\r\n\r\n if (message.items.length !== 4)\r\n throw new CoseError(`A COSE_Sign1 message must be a CBOR array of 4 elements, but had ${String(message.items.length)} element(s)!`);\r\n\r\n const [protectedBytes, unprotected, payload, signature] = message.items;\r\n\r\n if (protectedBytes?.type !== 'bytes')\r\n throw new CoseError('The protected header bucket of a COSE_Sign1 message must be a byte string!');\r\n\r\n if (unprotected === undefined)\r\n throw new CoseError('A COSE_Sign1 message must carry an unprotected header bucket!');\r\n\r\n if (payload === undefined || (payload.type !== 'null' && payload.type !== 'bytes'))\r\n throw new CoseError('The payload of a COSE_Sign1 message must be a byte string, or null when it is detached!');\r\n\r\n if (signature?.type !== 'bytes')\r\n throw new CoseError('The signature of a COSE_Sign1 message must be a byte string!');\r\n\r\n return new CoseSign1(protectedBytes.value,\r\n CoseHeaders.parse(unprotected),\r\n payload.type === 'bytes' ? payload.value : null,\r\n signature.value,\r\n isTagged);\r\n\r\n }\r\n\r\n\r\n /** A CBOR representation of this message. */\r\n public toCbor(): CborValue {\r\n\r\n const message = cbor.array([\r\n cbor.bytes(this.protectedHeaderBytes),\r\n this.unprotectedHeader.toCbor(),\r\n this.payload !== null ? cbor.bytes(this.payload) : cbor.nullValue,\r\n cbor.bytes(this.signature),\r\n ]);\r\n\r\n return this.isTagged ? cbor.tag(COSE_SIGN1_TAG, message) : message;\r\n\r\n }\r\n\r\n\r\n /** The CBOR encoding of this message. */\r\n public toBytes(): Uint8Array {\r\n return encode(this.toCbor());\r\n }\r\n\r\n\r\n /**\r\n * A copy of this message without its payload, e.g. because the payload\r\n * travels elsewhere.\r\n *\r\n * The signature stays valid: it never covered the message, only the\r\n * Sig_structure.\r\n */\r\n public detach(): CoseSign1 {\r\n return new CoseSign1(this.protectedHeaderBytes, this.unprotectedHeader,\r\n null, this.signature, this.isTagged);\r\n }\r\n\r\n\r\n /** A copy of this message carrying the given payload again. */\r\n public attach(payload: Uint8Array): CoseSign1 {\r\n\r\n if (this.payload !== null && !bytesEqual(this.payload, payload))\r\n throw new CoseError('This COSE_Sign1 message already carries a different payload!');\r\n\r\n return new CoseSign1(this.protectedHeaderBytes, this.unprotectedHeader,\r\n payload, this.signature, this.isTagged);\r\n\r\n }\r\n\r\n}\r\n\r\n\r\n/**\r\n * The last step every verification shares: the arithmetic, and the two ways of\r\n * failing that are not a wrong signature.\r\n */\r\nfunction verifySignature(algorithm: CoseAlgorithm,\r\n key: CoseKey,\r\n toBeSigned: Uint8Array,\r\n signature: Uint8Array): Verification {\r\n\r\n let publicKey: Uint8Array;\r\n\r\n try {\r\n publicKey = key.publicKeyBytes();\r\n }\r\n catch (cause) {\r\n return notVerified(cause instanceof Error ? cause.message : String(cause));\r\n }\r\n\r\n try {\r\n return verifyWith(algorithm, key.curve, toBeSigned, signature, publicKey)\r\n ? VERIFIED\r\n : notVerified('The signature is not valid for this payload and this key!');\r\n }\r\n catch (cause) {\r\n return notVerified(cause instanceof Error ? cause.message : String(cause));\r\n }\r\n\r\n}\r\n\r\n\r\nexport { verifySignature };\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * A COSE_Sign message [RFC 9052, Section 4.1]: one payload, several signers,\r\n * tagged with CBOR tag 98.\r\n *\r\n * <code>\r\n * COSE_Sign = [\r\n * protected : bstr .cbor header_map,\r\n * unprotected : header_map,\r\n * payload : bstr / nil,\r\n * signatures : [ + COSE_Signature ]\r\n * ]\r\n * </code>\r\n *\r\n * The signatures are independent: each covers the body, its own header bucket\r\n * and the payload, but never another signature. Adding one therefore leaves\r\n * the existing ones byte-for-byte valid, and the second party never needs the\r\n * first party's key.\r\n *\r\n * Which of the two mechanisms to reach for is decided by one question: does\r\n * the party have something of its own to say? Several parties asserting *the\r\n * same* payload is this. A party that vouches for somebody else's signature\r\n * without adding a claim wants the countersignature of RFC 9338, which lives\r\n * on COSE_Sign1. A party with metadata of its own signs a new payload that\r\n * nests the old message.\r\n *\r\n * Its Sig_structure has **five** elements rather than four, with the protected\r\n * bucket of the individual signature between the body and the external data.\r\n */\r\n\r\nimport { signWith } from './algorithm.ts';\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport { bytesEqual, cbor, decode,\r\n encode, NO_BYTES } from './cbor.ts';\r\nimport type { CborValue } from './cbor.ts';\r\nimport { CoseError, notVerified } from './errors.ts';\r\nimport type { Verification } from './errors.ts';\r\nimport { canonicalizePayload } from './payload.ts';\r\nimport { CoseHeaders,\r\n verifyCriticalHeaderParameters } from './headers.ts';\r\nimport type { CoseKey } from './key.ts';\r\nimport { resolveAlgorithm, resolvePayload } from './resolve.ts';\r\nimport { CoseSignature } from './signature.ts';\r\nimport { verifySignature } from './sign1.ts';\r\nimport type { Sign1Options, VerifyOptions } from './sign1.ts';\r\n\r\n\r\n/** The CBOR tag of a COSE_Sign message. */\r\nexport const COSE_SIGN_TAG = 98;\r\n\r\n/** The context string of a COSE_Sign signature [RFC 9052, Section 4.4]. */\r\nexport const SIGNATURE_CONTEXT = 'Signature';\r\n\r\n\r\nexport class CoseSign {\r\n\r\n /** The serialized protected bucket of the body, exactly as signed. */\r\n public readonly protectedHeaderBytes: Uint8Array;\r\n\r\n /** The protected header parameters of the body, which every signature covers. */\r\n public readonly protectedHeader: CoseHeaders;\r\n\r\n /** The unprotected header parameters of the body, which none of them covers. */\r\n public readonly unprotectedHeader: CoseHeaders;\r\n\r\n /** The signed payload, or null when it is detached. */\r\n public readonly payload: Uint8Array | null;\r\n\r\n /** The signatures, in the order they travel. */\r\n public readonly signatures: readonly CoseSignature[];\r\n\r\n /** Whether this message is wrapped within CBOR tag 98. */\r\n public readonly isTagged: boolean;\r\n\r\n\r\n public constructor(protectedHeaderBytes: Uint8Array,\r\n unprotectedHeader: CoseHeaders | null,\r\n payload: Uint8Array | null,\r\n signatures: readonly CoseSignature[],\r\n isTagged = true) {\r\n\r\n if (signatures.length === 0)\r\n throw new CoseError('A COSE_Sign message must carry at least one signature!');\r\n\r\n this.protectedHeaderBytes = protectedHeaderBytes;\r\n this.protectedHeader = CoseHeaders.parseProtected(protectedHeaderBytes);\r\n this.unprotectedHeader = unprotectedHeader ?? CoseHeaders.empty;\r\n this.payload = payload;\r\n this.signatures = [...signatures];\r\n this.isTagged = isTagged;\r\n\r\n }\r\n\r\n\r\n /** Whether the payload is detached. */\r\n public get isDetached(): boolean {\r\n return this.payload === null;\r\n }\r\n\r\n\r\n /**\r\n * The encoded Sig_structure of one signature of a COSE_Sign message\r\n * [RFC 9052, Section 4.4]:\r\n *\r\n * <code>\r\n * Sig_structure = [\r\n * context : \"Signature\",\r\n * body_protected : empty_or_serialized_map,\r\n * sign_protected : empty_or_serialized_map,\r\n * external_aad : bstr,\r\n * payload : bstr\r\n * ]\r\n * </code>\r\n */\r\n public static toBeSigned(bodyProtectedHeaderBytes: Uint8Array,\r\n signatureProtectedHeaderBytes: Uint8Array,\r\n payload: Uint8Array,\r\n externalAad: Uint8Array | null = null): Uint8Array {\r\n\r\n return encode(cbor.array([\r\n cbor.text(SIGNATURE_CONTEXT),\r\n cbor.bytes(bodyProtectedHeaderBytes),\r\n cbor.bytes(signatureProtectedHeaderBytes),\r\n cbor.bytes(externalAad ?? NO_BYTES),\r\n cbor.bytes(payload),\r\n ]));\r\n\r\n }\r\n\r\n\r\n /** The encoded Sig_structure of one signature of this message. */\r\n public toBeSigned(signature: CoseSignature,\r\n options: { externalAad?: Uint8Array | null;\r\n detachedPayload?: Uint8Array | null } = {}): Uint8Array {\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Sign message');\r\n\r\n if (!payload.ok)\r\n throw new CoseError(payload.reason);\r\n\r\n return CoseSign.toBeSigned(this.protectedHeaderBytes,\r\n signature.protectedHeaderBytes,\r\n payload.value,\r\n options.externalAad ?? null);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Sign a payload, producing a message with one signature.\r\n *\r\n * The body's protected bucket stays empty: what a signer has to say about\r\n * its own signature — its algorithm, its key identifier — belongs to that\r\n * signature rather than to the body every other signer shares.\r\n */\r\n public static sign(payload: Uint8Array,\r\n key: CoseKey,\r\n options: Sign1Options = {}): CoseSign {\r\n\r\n const signed = options.canonicalizePayload === false\r\n ? payload\r\n : canonicalizePayload(payload);\r\n\r\n // A detached payload is the caller's to transmit, and every further\r\n // signer added later signs those very same bytes. Rewriting them here\r\n // would sign a spelling nobody else has.\r\n if (options.detachPayload === true && !bytesEqual(signed, payload))\r\n throw new CoseError('The payload of this COSE_Sign message is detached, so canonicalizing it here would sign bytes that nobody holds: canonicalize the payload yourself (canonicalizePayload), sign and transmit those, or pass canonicalizePayload: false to sign the payload exactly as it is!');\r\n\r\n return new CoseSign(NO_BYTES,\r\n CoseHeaders.empty,\r\n options.detachPayload === true ? null : signed,\r\n [signatureOver(NO_BYTES, signed, key, options)],\r\n options.tagged ?? true);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Return a copy of this message with one more signature.\r\n *\r\n * The existing signatures are untouched and stay valid, because no\r\n * signature ever covers another.\r\n */\r\n public addSignature(key: CoseKey,\r\n options: Sign1Options & {\r\n detachedPayload?: Uint8Array | null } = {}): CoseSign {\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Sign message');\r\n\r\n if (!payload.ok)\r\n throw new CoseError(payload.reason);\r\n\r\n return new CoseSign(this.protectedHeaderBytes,\r\n this.unprotectedHeader,\r\n this.payload,\r\n [...this.signatures,\r\n signatureOver(this.protectedHeaderBytes, payload.value, key, options)],\r\n this.isTagged);\r\n\r\n }\r\n\r\n\r\n /** Verify one signature of this message. */\r\n public verify(signature: CoseSignature,\r\n key: CoseKey,\r\n options: VerifyOptions = {}): Verification {\r\n\r\n if (!this.signatures.includes(signature))\r\n return notVerified('The given signature is not one of the signatures of this COSE_Sign message!');\r\n\r\n const bodyCritical = verifyCriticalHeaderParameters(this.protectedHeader,\r\n this.unprotectedHeader,\r\n options.alsoUnderstood ?? []);\r\n\r\n if (!bodyCritical.verified)\r\n return bodyCritical;\r\n\r\n const signatureCritical = verifyCriticalHeaderParameters(signature.protectedHeader,\r\n signature.unprotectedHeader,\r\n options.alsoUnderstood ?? []);\r\n\r\n if (!signatureCritical.verified)\r\n return signatureCritical;\r\n\r\n const algorithm = resolveAlgorithm(signature.protectedHeader,\r\n signature.unprotectedHeader,\r\n options.expectedAlgorithm ?? key.algorithm,\r\n 'This signature of a COSE_Sign message');\r\n\r\n if (!algorithm.ok)\r\n return notVerified(algorithm.reason);\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Sign message');\r\n\r\n if (!payload.ok)\r\n return notVerified(payload.reason);\r\n\r\n return verifySignature(algorithm.value,\r\n key,\r\n CoseSign.toBeSigned(this.protectedHeaderBytes,\r\n signature.protectedHeaderBytes,\r\n payload.value,\r\n options.externalAad ?? null),\r\n signature.signature);\r\n\r\n }\r\n\r\n\r\n /**\r\n * The first signature this key verifies, or null.\r\n *\r\n * Signatures are tried in wire order. A signature that states its\r\n * algorithm in the unprotected bucket only still needs an expected\r\n * algorithm to be accepted, here as everywhere else — which the key\r\n * supplies when it carries one, and otherwise nobody does.\r\n */\r\n public verifyAny(key: CoseKey,\r\n options: VerifyOptions = {}): CoseSignature | null {\r\n\r\n for (const signature of this.signatures) {\r\n if (this.verify(signature, key, options).verified)\r\n return signature;\r\n }\r\n\r\n return null;\r\n\r\n }\r\n\r\n\r\n /** Parse a COSE_Sign message, tagged or untagged. */\r\n public static parse(input: Uint8Array | CborValue): CoseSign {\r\n\r\n const value = input instanceof Uint8Array ? decode(input) : input;\r\n\r\n let isTagged = false;\r\n let message = value;\r\n\r\n if (message.type === 'tag') {\r\n\r\n if (message.tag !== BigInt(COSE_SIGN_TAG))\r\n throw new CoseError(`A COSE_Sign message must be tagged with CBOR tag ${String(COSE_SIGN_TAG)}, but was tagged with CBOR tag ${String(message.tag)}!`);\r\n\r\n isTagged = true;\r\n message = message.value;\r\n\r\n }\r\n\r\n if (message.type !== 'array')\r\n throw new CoseError(`A COSE_Sign message must be a CBOR array, but was a CBOR ${message.type}!`);\r\n\r\n if (message.items.length !== 4)\r\n throw new CoseError(`A COSE_Sign message must be a CBOR array of 4 elements, but had ${String(message.items.length)} element(s)!`);\r\n\r\n const [protectedBytes, unprotected, payload, signatures] = message.items;\r\n\r\n if (protectedBytes?.type !== 'bytes')\r\n throw new CoseError('The protected header bucket of a COSE_Sign message must be a byte string!');\r\n\r\n if (unprotected === undefined)\r\n throw new CoseError('A COSE_Sign message must carry an unprotected header bucket!');\r\n\r\n if (payload === undefined || (payload.type !== 'null' && payload.type !== 'bytes'))\r\n throw new CoseError('The payload of a COSE_Sign message must be a byte string, or null when it is detached!');\r\n\r\n if (signatures?.type !== 'array')\r\n throw new CoseError('The signatures of a COSE_Sign message must be a CBOR array!');\r\n\r\n return new CoseSign(protectedBytes.value,\r\n CoseHeaders.parse(unprotected),\r\n payload.type === 'bytes' ? payload.value : null,\r\n signatures.items.map(each => CoseSignature.parse(each)),\r\n isTagged);\r\n\r\n }\r\n\r\n\r\n /** A CBOR representation of this message. */\r\n public toCbor(): CborValue {\r\n\r\n const message = cbor.array([\r\n cbor.bytes(this.protectedHeaderBytes),\r\n this.unprotectedHeader.toCbor(),\r\n this.payload !== null ? cbor.bytes(this.payload) : cbor.nullValue,\r\n cbor.array(this.signatures.map(each => each.toCbor())),\r\n ]);\r\n\r\n return this.isTagged ? cbor.tag(COSE_SIGN_TAG, message) : message;\r\n\r\n }\r\n\r\n\r\n /** The CBOR encoding of this message. */\r\n public toBytes(): Uint8Array {\r\n return encode(this.toCbor());\r\n }\r\n\r\n}\r\n\r\n\r\n/** Sign one signature slot of a COSE_Sign message. */\r\nfunction signatureOver(bodyProtectedHeaderBytes: Uint8Array,\r\n payload: Uint8Array,\r\n key: CoseKey,\r\n options: Sign1Options): CoseSignature {\r\n\r\n const algorithm: CoseAlgorithm | null = key.algorithm;\r\n\r\n if (algorithm === null)\r\n throw new CoseError('The COSE key does not name the signature algorithm to use!');\r\n\r\n const keyIdentifier = options.keyIdentifier === undefined\r\n ? key.keyIdentifier\r\n : options.keyIdentifier;\r\n\r\n const protectedBytes = CoseHeaders.create(algorithm).toProtectedBytes();\r\n\r\n const signature = signWith(algorithm,\r\n key.curve,\r\n CoseSign.toBeSigned(bodyProtectedHeaderBytes,\r\n protectedBytes,\r\n payload,\r\n options.externalAad ?? null),\r\n key.privateKeyBytes());\r\n\r\n return new CoseSignature(protectedBytes,\r\n keyIdentifier !== null\r\n ? CoseHeaders.create(null, keyIdentifier)\r\n : CoseHeaders.empty,\r\n signature);\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * A COSE_Mac0 message [RFC 9052, Section 6.2]: a payload authenticated with a\r\n * key both parties hold, tagged with CBOR tag 17.\r\n *\r\n * <code>\r\n * COSE_Mac0 = [\r\n * protected : bstr .cbor header_map, ; covered by the tag\r\n * unprotected : header_map, ; NOT covered by the tag\r\n * payload : bstr / nil, ; nil = detached\r\n * tag : bstr\r\n * ]\r\n * </code>\r\n *\r\n * It is the structural twin of `COSE_Sign1`, deliberately: four elements in\r\n * the same order, tag 17 against tag 18, and a MAC_structure that differs from\r\n * the Sig_structure in one string — `\"MAC0\"` where the other says\r\n * `\"Signature1\"`. Everything the signature code learned applies unchanged: the\r\n * protected bucket is kept verbatim, the CBOR tag is not covered, the payload\r\n * may be detached, external additional authenticated data is signed without\r\n * travelling.\r\n *\r\n * **What is not the same is what a verified message means.** A signature says\r\n * \"the holder of that private key produced this\", to anybody who cares to\r\n * check. A tag says \"someone holding the shared key produced this\", and only\r\n * to someone who holds that key too — because verifying one requires the very\r\n * key that creates one. Between two parties that is still useful: each knows\r\n * the other made it, having not made it themselves. Towards a third party it\r\n * is worth nothing at all, and a party that later denies having produced a\r\n * message cannot be contradicted with a tag.\r\n *\r\n * That is why a metrological record is *signed*. The customer, the operator\r\n * and the regulator all have to be able to check a reading, and none of them\r\n * may be able to manufacture one. A MAC belongs where the two ends of a link\r\n * already share a secret and want cheap tamper detection — eight bytes and one\r\n * hash, against sixty-four bytes and a curve multiplication — with the durable\r\n * evidence carried by a signature underneath.\r\n *\r\n * The `tag` field is an authentication tag and has nothing to do with the CBOR\r\n * tag 17 this message is wrapped in. RFC 9052 uses the word for both.\r\n */\r\n\r\nimport { macWith, verifyMacWith } from './algorithm.ts';\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport { bytesEqual, cbor, decode,\r\n encode, NO_BYTES } from './cbor.ts';\r\nimport type { CborValue } from './cbor.ts';\r\nimport { CoseError, notVerified, VERIFIED } from './errors.ts';\r\nimport type { Verification } from './errors.ts';\r\nimport { CoseHeaders,\r\n verifyCriticalHeaderParameters } from './headers.ts';\r\nimport { KEY_TYPE_SYMMETRIC } from './key.ts';\r\nimport type { CoseKey } from './key.ts';\r\nimport { HeaderLabel, label } from './labels.ts';\r\nimport { canonicalizePayload } from './payload.ts';\r\nimport { resolveAlgorithm, resolvePayload } from './resolve.ts';\r\n\r\n\r\n/** The CBOR tag of a COSE_Mac0 message. */\r\nexport const COSE_MAC0_TAG = 17;\r\n\r\n/** The context string of a COSE_Mac0 authentication tag [RFC 9052, Section 6.3]. */\r\nexport const MAC0_CONTEXT = 'MAC0';\r\n\r\n\r\n/** What a party computing an authentication tag may choose. */\r\nexport interface Mac0Options {\r\n\r\n /** A key identifier for the unprotected bucket, defaulting to the key's own. */\r\n readonly keyIdentifier?: Uint8Array | null;\r\n\r\n /** Data authenticated along with the payload without travelling in the message. */\r\n readonly externalAad?: Uint8Array | null;\r\n\r\n /** Whether to omit the payload from the message. */\r\n readonly detachPayload?: boolean;\r\n\r\n /**\r\n * Whether to rewrite a CBOR payload in the deterministic encoding of\r\n * RFC 8949 §4.2.1 before authenticating it, so that a receiver who parses\r\n * and re-serializes the record arrives at the very bytes this tag covers.\r\n * Defaults to true. A payload that is not CBOR is authenticated as it is.\r\n */\r\n readonly canonicalizePayload?: boolean;\r\n\r\n\r\n /** Whether to wrap the message within CBOR tag 17. Defaults to true. */\r\n readonly tagged?: boolean;\r\n\r\n}\r\n\r\n\r\n/** What a party checking an authentication tag may have to supply. */\r\nexport interface Mac0VerifyOptions {\r\n\r\n /** The data that was authenticated along with the payload. */\r\n readonly externalAad?: Uint8Array | null;\r\n\r\n /** The payload, when the message carries a detached one. */\r\n readonly detachedPayload?: Uint8Array | null;\r\n\r\n /**\r\n * The algorithm the caller expects, required whenever the message states\r\n * its algorithm within the unprotected bucket only.\r\n */\r\n readonly expectedAlgorithm?: CoseAlgorithm | null;\r\n\r\n /**\r\n * Header parameters the caller processes itself, and which a `crit`\r\n * header parameter may therefore demand.\r\n */\r\n readonly alsoUnderstood?: readonly CborValue[];\r\n\r\n}\r\n\r\n\r\nexport class CoseMac0 {\r\n\r\n /**\r\n * The serialized protected bucket, exactly as authenticated and as\r\n * received: a zero-length byte string when there are no protected header\r\n * parameters.\r\n */\r\n public readonly protectedHeaderBytes: Uint8Array;\r\n\r\n /** The protected header parameters, which the authentication tag covers. */\r\n public readonly protectedHeader: CoseHeaders;\r\n\r\n /**\r\n * The unprotected header parameters, which the tag does not cover and\r\n * which therefore must not be trusted after a successful verification.\r\n */\r\n public readonly unprotectedHeader: CoseHeaders;\r\n\r\n /** The authenticated payload, or null when it is detached. */\r\n public readonly payload: Uint8Array | null;\r\n\r\n /** The authentication tag — not the CBOR tag. */\r\n public readonly tag: Uint8Array;\r\n\r\n /**\r\n * Whether this message is wrapped within CBOR tag 17. The tag is not\r\n * covered by the authentication tag, but it is preserved so that a parsed\r\n * message re-encodes to the very same bytes.\r\n */\r\n public readonly isTagged: boolean;\r\n\r\n\r\n public constructor(protectedHeaderBytes: Uint8Array,\r\n unprotectedHeader: CoseHeaders | null,\r\n payload: Uint8Array | null,\r\n tag: Uint8Array,\r\n isTagged = true) {\r\n\r\n this.protectedHeaderBytes = protectedHeaderBytes;\r\n this.protectedHeader = CoseHeaders.parseProtected(protectedHeaderBytes);\r\n this.unprotectedHeader = unprotectedHeader ?? CoseHeaders.empty;\r\n this.payload = payload;\r\n this.tag = tag;\r\n this.isTagged = isTagged;\r\n\r\n }\r\n\r\n\r\n /** Whether the payload is detached. */\r\n public get isDetached(): boolean {\r\n return this.payload === null;\r\n }\r\n\r\n /**\r\n * The MAC algorithm, taken from the protected bucket and only otherwise\r\n * from the unprotected one.\r\n */\r\n public get algorithm(): CoseAlgorithm | null {\r\n return this.protectedHeader.algorithm ?? this.unprotectedHeader.algorithm;\r\n }\r\n\r\n /** The key identifier, protected bucket first. */\r\n public get keyIdentifier(): Uint8Array | null {\r\n return this.protectedHeader.keyIdentifier ?? this.unprotectedHeader.keyIdentifier;\r\n }\r\n\r\n\r\n // ----------------------------------------------------- the MAC_structure\r\n\r\n /**\r\n * The encoded MAC_structure [RFC 9052, Section 6.3], which is the byte\r\n * string the MAC is actually computed over:\r\n *\r\n * <code>\r\n * MAC_structure = [\r\n * context : \"MAC0\",\r\n * protected : empty_or_serialized_map,\r\n * external_aad : bstr,\r\n * payload : bstr\r\n * ]\r\n * </code>\r\n *\r\n * The full payload goes in here regardless of how it travels, so a\r\n * detached message and an attached one carry the very same tag.\r\n */\r\n public static toBeMaced(protectedHeaderBytes: Uint8Array,\r\n payload: Uint8Array,\r\n externalAad: Uint8Array | null = null): Uint8Array {\r\n\r\n return encode(cbor.array([\r\n cbor.text(MAC0_CONTEXT),\r\n cbor.bytes(protectedHeaderBytes),\r\n cbor.bytes(externalAad ?? NO_BYTES),\r\n cbor.bytes(payload),\r\n ]));\r\n\r\n }\r\n\r\n\r\n /** The encoded MAC_structure of this message. */\r\n public toBeMaced(options: { externalAad?: Uint8Array | null;\r\n detachedPayload?: Uint8Array | null } = {}): Uint8Array {\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Mac0 message');\r\n\r\n if (!payload.ok)\r\n throw new CoseError(payload.reason);\r\n\r\n return CoseMac0.toBeMaced(this.protectedHeaderBytes,\r\n payload.value,\r\n options.externalAad ?? null);\r\n\r\n }\r\n\r\n\r\n // --------------------------------------------------------------- creating\r\n\r\n /**\r\n * Authenticate a payload, placing the algorithm within the protected\r\n * bucket and the key identifier within the unprotected one.\r\n */\r\n public static create(payload: Uint8Array,\r\n key: CoseKey,\r\n options: Mac0Options = {}): CoseMac0 {\r\n\r\n const algorithm = requireMacAlgorithm(key);\r\n\r\n const keyIdentifier = options.keyIdentifier === undefined\r\n ? key.keyIdentifier\r\n : options.keyIdentifier;\r\n\r\n const protectedHeader = new CoseHeaders([\r\n [label(HeaderLabel.algorithm), cbor.int(algorithm.id)],\r\n ]);\r\n\r\n return CoseMac0.createWithHeaders(payload, key, protectedHeader,\r\n keyIdentifier === null\r\n ? null\r\n : new CoseHeaders([[label(HeaderLabel.keyIdentifier),\r\n cbor.bytes(keyIdentifier)]]),\r\n options);\r\n\r\n }\r\n\r\n\r\n /** Authenticate a payload with header buckets the caller composed. */\r\n public static createWithHeaders(payload: Uint8Array,\r\n key: CoseKey,\r\n protectedHeader: CoseHeaders,\r\n unprotectedHeader: CoseHeaders | null = null,\r\n options: Mac0Options = {}): CoseMac0 {\r\n\r\n const stated = protectedHeader.algorithm;\r\n const algorithm = stated ?? requireMacAlgorithm(key);\r\n\r\n requireSymmetric(key, algorithm);\r\n\r\n const protectedBytes = protectedHeader.toProtectedBytes();\r\n\r\n // A MAC dies the same death as a signature: a receiver that decodes\r\n // the payload and encodes it again produces the deterministic\r\n // spelling, and a tag over another one no longer verifies. A detached\r\n // payload is the caller's to transmit, so rewriting it here would\r\n // authenticate bytes nobody holds.\r\n const authenticated = options.canonicalizePayload === false\r\n ? payload\r\n : canonicalizePayload(payload);\r\n\r\n if (options.detachPayload === true && !bytesEqual(authenticated, payload))\r\n throw new CoseError('The payload of this COSE_Mac0 message is detached, so canonicalizing it here would authenticate bytes that nobody holds: canonicalize the payload yourself (canonicalizePayload), authenticate and transmit those, or pass canonicalizePayload: false to authenticate the payload exactly as it is!');\r\n\r\n const tag = macWith(algorithm,\r\n CoseMac0.toBeMaced(protectedBytes, authenticated, options.externalAad ?? null),\r\n key.privateKeyBytes());\r\n\r\n return new CoseMac0(protectedBytes,\r\n unprotectedHeader,\r\n options.detachPayload === true ? null : authenticated,\r\n tag,\r\n options.tagged ?? true);\r\n\r\n }\r\n\r\n\r\n // ----------------------------------------------------------- verification\r\n\r\n /**\r\n * Verify the authentication tag of this message.\r\n *\r\n * A failed verification is not an exception — it is the expected outcome\r\n * of checking untrusted data — so the reason travels in the result. The\r\n * comparison itself is constant time, which matters here in a way it does\r\n * not for a signature: an early-returning compare would tell whoever is\r\n * guessing a tag how many of their leading bytes were right.\r\n */\r\n public verify(key: CoseKey, options: Mac0VerifyOptions = {}): Verification {\r\n\r\n const critical = verifyCriticalHeaderParameters(this.protectedHeader,\r\n this.unprotectedHeader,\r\n options.alsoUnderstood ?? []);\r\n\r\n if (!critical.verified)\r\n return critical;\r\n\r\n const algorithm = resolveAlgorithm(this.protectedHeader,\r\n this.unprotectedHeader,\r\n options.expectedAlgorithm ?? key.algorithm,\r\n 'This COSE_Mac0 message');\r\n\r\n if (!algorithm.ok)\r\n return notVerified(algorithm.reason);\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Mac0 message');\r\n\r\n if (!payload.ok)\r\n return notVerified(payload.reason);\r\n\r\n if (algorithm.value.family !== 'hmac')\r\n return notVerified(`The COSE algorithm '${algorithm.value.name}' is not a message authentication algorithm: a COSE_Mac0 message can not be authenticated with a signature algorithm!`);\r\n\r\n if (key.keyType !== KEY_TYPE_SYMMETRIC)\r\n return notVerified(`A COSE_Mac0 message needs a key of key type Symmetric [RFC 9053, Section 3.1], but a key of key type ${String(key.keyType)} was given!`);\r\n\r\n let verified: boolean;\r\n\r\n try {\r\n verified = verifyMacWith(algorithm.value,\r\n CoseMac0.toBeMaced(this.protectedHeaderBytes,\r\n payload.value,\r\n options.externalAad ?? null),\r\n this.tag,\r\n key.privateKeyBytes());\r\n }\r\n catch (exception) {\r\n return notVerified(exception instanceof Error ? exception.message : String(exception));\r\n }\r\n\r\n return verified\r\n ? VERIFIED\r\n : notVerified('The authentication tag is not the right one for this payload and this key!');\r\n\r\n }\r\n\r\n\r\n // ------------------------------------------------------- serialization\r\n\r\n /** Read a COSE_Mac0 message, tagged or not. */\r\n public static parse(input: Uint8Array | CborValue): CoseMac0 {\r\n\r\n const value = input instanceof Uint8Array ? decode(input) : input;\r\n\r\n let isTagged = false;\r\n let message = value;\r\n\r\n if (message.type === 'tag') {\r\n\r\n if (message.tag !== BigInt(COSE_MAC0_TAG))\r\n throw new CoseError(`A COSE_Mac0 message must be tagged with CBOR tag ${String(COSE_MAC0_TAG)}, but was tagged with CBOR tag ${String(message.tag)}!`);\r\n\r\n isTagged = true;\r\n message = message.value;\r\n\r\n }\r\n\r\n if (message.type !== 'array')\r\n throw new CoseError(`A COSE_Mac0 message must be a CBOR array, but was a CBOR ${message.type}!`);\r\n\r\n if (message.items.length !== 4)\r\n throw new CoseError(`A COSE_Mac0 message must be a CBOR array of 4 elements, but had ${String(message.items.length)} element(s)!`);\r\n\r\n const [protectedBytes, unprotected, payload, tag] = message.items;\r\n\r\n if (protectedBytes?.type !== 'bytes')\r\n throw new CoseError('The protected header bucket of a COSE_Mac0 message must be a byte string!');\r\n\r\n if (unprotected === undefined)\r\n throw new CoseError('A COSE_Mac0 message must carry an unprotected header bucket!');\r\n\r\n if (payload === undefined || (payload.type !== 'null' && payload.type !== 'bytes'))\r\n throw new CoseError('The payload of a COSE_Mac0 message must be a byte string, or null when it is detached!');\r\n\r\n if (tag?.type !== 'bytes')\r\n throw new CoseError('The authentication tag of a COSE_Mac0 message must be a byte string!');\r\n\r\n return new CoseMac0(protectedBytes.value,\r\n CoseHeaders.parse(unprotected),\r\n payload.type === 'bytes' ? payload.value : null,\r\n tag.value,\r\n isTagged);\r\n\r\n }\r\n\r\n\r\n /** The CBOR form of this message. */\r\n public toCbor(): CborValue {\r\n\r\n const message = cbor.array([\r\n cbor.bytes(this.protectedHeaderBytes),\r\n this.unprotectedHeader.toCbor(),\r\n this.payload !== null ? cbor.bytes(this.payload) : cbor.nullValue,\r\n cbor.bytes(this.tag),\r\n ]);\r\n\r\n return this.isTagged ? cbor.tag(COSE_MAC0_TAG, message) : message;\r\n\r\n }\r\n\r\n\r\n /** The CBOR encoding of this message. */\r\n public toBytes(): Uint8Array {\r\n return encode(this.toCbor());\r\n }\r\n\r\n\r\n /**\r\n * A copy of this message without its payload.\r\n *\r\n * The tag stays valid: it never covered the message, only the\r\n * MAC_structure, and the MAC_structure always holds the full payload.\r\n */\r\n public detach(): CoseMac0 {\r\n return new CoseMac0(this.protectedHeaderBytes, this.unprotectedHeader,\r\n null, this.tag, this.isTagged);\r\n }\r\n\r\n}\r\n\r\n\r\n/** The MAC algorithm a key names, refusing a key that names something else. */\r\nfunction requireMacAlgorithm(key: CoseKey): CoseAlgorithm {\r\n\r\n if (key.algorithm === null)\r\n throw new CoseError('A COSE_Mac0 message needs a MAC algorithm: either on the key or within the protected header bucket!');\r\n\r\n if (key.algorithm.family !== 'hmac')\r\n throw new CoseError(`The COSE algorithm '${key.algorithm.name}' is not a message authentication algorithm!`);\r\n\r\n return key.algorithm;\r\n\r\n}\r\n\r\n\r\n/**\r\n * The key checks of RFC 9053 Section 3.1.\r\n *\r\n * The second one is the one worth having. A key that names `HMAC 256/256`\r\n * being used to produce an `HMAC 256/64` tag is a truncation nobody asked for,\r\n * and it is exactly how a party talks itself into a weaker tag than the key\r\n * was issued for.\r\n */\r\nfunction requireSymmetric(key: CoseKey, algorithm: CoseAlgorithm): void {\r\n\r\n if (algorithm.family !== 'hmac')\r\n throw new CoseError(`The COSE algorithm '${algorithm.name}' is not a message authentication algorithm!`);\r\n\r\n if (key.keyType !== KEY_TYPE_SYMMETRIC)\r\n throw new CoseError(`A COSE_Mac0 message needs a key of key type Symmetric [RFC 9053, Section 3.1], but a key of key type ${String(key.keyType)} was given!`);\r\n\r\n if (key.algorithm !== null && key.algorithm.id !== algorithm.id)\r\n throw new CoseError(`This message is to be authenticated with '${algorithm.name}', but the key names '${key.algorithm.name}' [RFC 9053, Section 3.1]!`);\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * The two AES constructions COSE needs: **AES-GCM** for content encryption\r\n * [RFC 9053, Section 4.1] and **AES key wrap** for delivering a content key to\r\n * a recipient [RFC 9053, Section 6.2.1, RFC 3394].\r\n *\r\n * They do very different jobs and it is worth keeping them apart in one's head.\r\n * GCM protects a *payload*: it produces ciphertext plus an authentication tag,\r\n * and it authenticates additional data — the `Enc_structure` — that is never\r\n * encrypted. Key wrap protects a *key*: a short, high-entropy secret, under\r\n * another key, with no additional data and no nonce at all.\r\n *\r\n * That last point is the one that surprises people. AES key wrap is\r\n * deterministic: the same key wrapped under the same key-encryption key yields\r\n * the same 40 bytes every time. It is safe because what it wraps is a\r\n * uniformly random key rather than a message — RFC 3394 relies on that\r\n * squarely, and wrapping anything guessable with it is a mistake the API\r\n * cannot prevent.\r\n *\r\n * Both come from `@noble/ciphers` — the same audited family the curves, the\r\n * hashes and ML-DSA already come from — rather than from `node:crypto` or\r\n * WebCrypto: the former exists only under Node, the latter only behind an\r\n * `async` API, and this library runs wherever its CBOR codec runs, which\r\n * includes browsers.\r\n */\r\n\r\nimport { aeskw, gcm } from '@noble/ciphers/aes.js';\r\n\r\nimport { CoseError } from './errors.ts';\r\n\r\n\r\n/** The nonce width AES-GCM is fixed to in COSE: 96 bits [RFC 9053, Section 4.1]. */\r\nexport const GCM_NONCE_SIZE = 12;\r\n\r\n/** The authentication tag width AES-GCM is fixed to in COSE: 128 bits. */\r\nexport const GCM_TAG_SIZE = 16;\r\n\r\n// The library checks key widths itself, but with its own error type and its\r\n// own words. The refusal is this module's contract, so it happens here first.\r\nfunction checkKeySize(keySize: number, what: string): void {\r\n\r\n if (keySize !== 16 && keySize !== 24 && keySize !== 32)\r\n throw new CoseError(`${what} needs a key of 16, 24 or 32 bytes, but a ${String(keySize)}-byte key was given!`);\r\n\r\n}\r\n\r\n\r\n/**\r\n * Encrypt with AES-GCM.\r\n *\r\n * The returned byte string is `ciphertext ‖ tag`, which is how COSE carries it\r\n * — the authentication tag is not a field of its own, it is the last sixteen\r\n * bytes of the ciphertext. An implementation keeping them apart interoperates\r\n * with nothing.\r\n *\r\n * `additionalData` is the encoded `Enc_structure`: authenticated, never\r\n * encrypted, and never transported, because the recipient rebuilds it from the\r\n * message.\r\n */\r\nexport function aesGcmEncrypt(key: Uint8Array,\r\n nonce: Uint8Array,\r\n plaintext: Uint8Array,\r\n additionalData: Uint8Array): Uint8Array {\r\n\r\n if (nonce.length !== GCM_NONCE_SIZE)\r\n throw new CoseError(`AES-GCM within COSE uses a ${String(GCM_NONCE_SIZE)}-byte nonce [RFC 9053, Section 4.1], but a ${String(nonce.length)}-byte one was given!`);\r\n\r\n checkKeySize(key.length, 'AES-GCM');\r\n\r\n return gcm(key, nonce, additionalData).encrypt(plaintext);\r\n\r\n}\r\n\r\n\r\n/**\r\n * Decrypt with AES-GCM, or say why not.\r\n *\r\n * A failed decryption is not an exception here for the same reason a failed\r\n * signature verification is not: it is the expected outcome of processing\r\n * untrusted data. And an AEAD failure means the *whole* message is\r\n * unauthenticated, so there is no partial plaintext to hand back — anything\r\n * decrypted before the tag was checked must be discarded, which is precisely\r\n * what makes releasing unverified plaintext the classic AEAD mistake.\r\n */\r\nexport function aesGcmDecrypt(key: Uint8Array,\r\n nonce: Uint8Array,\r\n ciphertext: Uint8Array,\r\n additionalData: Uint8Array): Uint8Array | null {\r\n\r\n if (nonce.length !== GCM_NONCE_SIZE)\r\n throw new CoseError(`AES-GCM within COSE uses a ${String(GCM_NONCE_SIZE)}-byte nonce [RFC 9053, Section 4.1], but a ${String(nonce.length)}-byte one was given!`);\r\n\r\n if (ciphertext.length < GCM_TAG_SIZE)\r\n return null;\r\n\r\n checkKeySize(key.length, 'AES-GCM');\r\n\r\n try {\r\n // The library takes `ciphertext ‖ tag` in one piece, exactly as COSE\r\n // carries it, and throws exactly when the tag does not check out.\r\n // There is nothing to report beyond that, and reporting more would be\r\n // a padding-oracle of one's own making.\r\n return gcm(key, nonce, additionalData).decrypt(ciphertext);\r\n }\r\n catch {\r\n return null;\r\n }\r\n\r\n}\r\n\r\n\r\n/**\r\n * Wrap a content key under a key-encryption key [RFC 3394].\r\n *\r\n * The result is eight bytes longer than the key: the integrity check value of\r\n * RFC 3394 travels with it, which is what makes an unwrap able to fail rather\r\n * than silently return rubbish.\r\n */\r\nexport function aesKeyWrap(keyEncryptionKey: Uint8Array,\r\n contentKey: Uint8Array): Uint8Array {\r\n\r\n if (contentKey.length % 8 !== 0 || contentKey.length < 16)\r\n throw new CoseError(`AES key wrap needs a key of at least 16 bytes and a multiple of 8 [RFC 3394], but a ${String(contentKey.length)}-byte key was given!`);\r\n\r\n checkKeySize(keyEncryptionKey.length, 'AES key wrap');\r\n\r\n return aeskw(keyEncryptionKey).encrypt(contentKey);\r\n\r\n}\r\n\r\n\r\n/**\r\n * Unwrap a content key, or return null when the integrity check fails.\r\n *\r\n * Failing is the useful behaviour: RFC 3394's check value is what tells a\r\n * recipient that this wrapped key was not meant for them, rather than handing\r\n * them a plausible-looking key that decrypts nothing.\r\n */\r\nexport function aesKeyUnwrap(keyEncryptionKey: Uint8Array,\r\n wrapped: Uint8Array): Uint8Array | null {\r\n\r\n if (wrapped.length % 8 !== 0 || wrapped.length < 24)\r\n return null;\r\n\r\n try {\r\n // A key-encryption key of the wrong width throws here too, which for\r\n // an *unwrap* is the right shape: null, like any other failure to\r\n // unwrap what was given.\r\n return aeskw(keyEncryptionKey).decrypt(wrapped);\r\n }\r\n catch {\r\n return null;\r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * A COSE_recipient [RFC 9052, Section 5.1]: how a content key reaches one\r\n * party.\r\n *\r\n * ```\r\n * COSE_recipient = [\r\n * Headers,\r\n * ciphertext : bstr / nil,\r\n * ? recipients : [+COSE_recipient]\r\n * ]\r\n * ```\r\n *\r\n * This is what separates `COSE_Encrypt` from `COSE_Encrypt0` and `COSE_Mac`\r\n * from `COSE_Mac0`. The bare forms assume both parties already hold the key;\r\n * the enveloped forms solve the distribution problem **inside the message**.\r\n * One content key protects the body, and one recipient structure per party\r\n * delivers that key by a route only that party can walk.\r\n *\r\n * Two routes are implemented here, and they are the two reachable from a\r\n * pre-shared secret:\r\n *\r\n * - **`direct`** [RFC 9053, §6.1.1] — the recipient's key *is* the content\r\n * key. Nothing is transported: the protected bucket and the ciphertext are\r\n * both empty, and the structure exists only to name a key identifier.\r\n * - **AES key wrap** [RFC 9053, §6.2.1, RFC 3394] — the content key is\r\n * encrypted under a key-encryption key the recipient holds.\r\n *\r\n * Not implemented: ECDH key agreement and the HKDF-based key derivations. Both\r\n * need `COSE_KDF_Context` [RFC 9053, §5.2], a structure of its own carrying\r\n * PartyU and PartyV information and the supplementary public info — and one\r\n * whose fields, got subtly wrong, derive a key that agrees only with an\r\n * implementation making the same mistake. It is a piece of work in its own\r\n * right rather than a variation on this one.\r\n *\r\n * The `? recipients` at the end is not decoration: recipient structures nest,\r\n * so a key can be wrapped to a group whose key is in turn wrapped to its\r\n * members. Nesting is parsed and preserved here; building one is left to the\r\n * caller, who can pass nested recipients in.\r\n *\r\n * **What a recipient list costs in security, and it is not nothing.** Every\r\n * recipient of a `COSE_Mac` holds the same content key, so with more than one\r\n * of them a tag no longer even tells the recipients apart: any of them can\r\n * produce a message the others will accept as coming from the sender. RFC 9052\r\n * §8.2 puts it plainly — a MAC provides *\"either no or very limited data\r\n * origination\"*. For an encrypted message the same is true of its integrity\r\n * guarantee.\r\n */\r\n\r\nimport { algorithmToCbor, CoseAlgorithms } from './algorithm.ts';\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport { aesKeyUnwrap, aesKeyWrap } from './aes.ts';\r\nimport { cbor, NO_BYTES } from './cbor.ts';\r\nimport type { CborEntry, CborValue } from './cbor.ts';\r\nimport { CoseError } from './errors.ts';\r\nimport { CoseHeaders } from './headers.ts';\r\nimport { KEY_TYPE_SYMMETRIC } from './key.ts';\r\nimport type { CoseKey } from './key.ts';\r\nimport { HeaderLabel, label } from './labels.ts';\r\n\r\n\r\n/** What a party building a recipient structure may choose. */\r\nexport interface RecipientOptions {\r\n\r\n /** A key identifier for the unprotected bucket, defaulting to the key's own. */\r\n readonly keyIdentifier?: Uint8Array | null;\r\n\r\n /** Recipient structures nested below this one. */\r\n readonly recipients?: readonly CoseRecipient[];\r\n\r\n}\r\n\r\n\r\nexport class CoseRecipient {\r\n\r\n /** The serialized protected bucket — empty for both implemented routes. */\r\n public readonly protectedHeaderBytes: Uint8Array;\r\n\r\n /** The protected header parameters. */\r\n public readonly protectedHeader: CoseHeaders;\r\n\r\n /** The unprotected header parameters, which is where `alg` and `kid` live here. */\r\n public readonly unprotectedHeader: CoseHeaders;\r\n\r\n /** The wrapped content key, or a zero-length string for `direct`. */\r\n public readonly ciphertext: Uint8Array;\r\n\r\n /** Recipient structures nested below this one. */\r\n public readonly recipients: readonly CoseRecipient[];\r\n\r\n\r\n public constructor(protectedHeaderBytes: Uint8Array,\r\n unprotectedHeader: CoseHeaders | null,\r\n ciphertext: Uint8Array,\r\n recipients: readonly CoseRecipient[] = []) {\r\n\r\n this.protectedHeaderBytes = protectedHeaderBytes;\r\n this.protectedHeader = CoseHeaders.parseProtected(protectedHeaderBytes);\r\n this.unprotectedHeader = unprotectedHeader ?? CoseHeaders.empty;\r\n this.ciphertext = ciphertext;\r\n this.recipients = [...recipients];\r\n\r\n }\r\n\r\n\r\n /** The recipient algorithm, protected bucket first. */\r\n public get algorithm(): CoseAlgorithm | null {\r\n return this.protectedHeader.algorithm ?? this.unprotectedHeader.algorithm;\r\n }\r\n\r\n /** The key identifier, protected bucket first. */\r\n public get keyIdentifier(): Uint8Array | null {\r\n return this.protectedHeader.keyIdentifier ?? this.unprotectedHeader.keyIdentifier;\r\n }\r\n\r\n\r\n // ---------------------------------------------------------- constructing\r\n\r\n /**\r\n * A `direct` recipient: the key it names *is* the content key.\r\n *\r\n * RFC 9053 §6.1.1 requires the protected bucket to be zero length, and\r\n * nothing is carried in the ciphertext either — so this structure conveys\r\n * a key identifier and an algorithm and no key material at all.\r\n */\r\n public static direct(key: CoseKey, options: RecipientOptions = {}): CoseRecipient {\r\n\r\n requireSymmetric(key, 'A direct recipient');\r\n\r\n return new CoseRecipient(NO_BYTES,\r\n headersFor(CoseAlgorithms.direct,\r\n options.keyIdentifier === undefined\r\n ? key.keyIdentifier\r\n : options.keyIdentifier),\r\n NO_BYTES,\r\n options.recipients ?? []);\r\n\r\n }\r\n\r\n\r\n /**\r\n * A key-wrap recipient: the content key, encrypted under the given\r\n * key-encryption key.\r\n *\r\n * The algorithm follows from the width of the *key-encryption* key rather\r\n * than from the content key, which is the direction people get wrong:\r\n * `A256KW` wraps a 128-bit content key perfectly well.\r\n */\r\n public static keyWrap(contentKey: Uint8Array,\r\n keyEncryptionKey: CoseKey,\r\n options: RecipientOptions = {}): CoseRecipient {\r\n\r\n requireSymmetric(keyEncryptionKey, 'A key-wrap recipient');\r\n\r\n const kek = keyEncryptionKey.privateKeyBytes();\r\n const algorithm = keyWrapAlgorithmFor(kek.length);\r\n\r\n if (keyEncryptionKey.algorithm !== null &&\r\n keyEncryptionKey.algorithm.id !== algorithm.id &&\r\n keyEncryptionKey.algorithm.family === 'keywrap')\r\n throw new CoseError(`The key-encryption key names '${keyEncryptionKey.algorithm.name}', but its ${String(kek.length)} bytes are '${algorithm.name}'!`);\r\n\r\n return new CoseRecipient(NO_BYTES,\r\n headersFor(algorithm,\r\n options.keyIdentifier === undefined\r\n ? keyEncryptionKey.keyIdentifier\r\n : options.keyIdentifier),\r\n aesKeyWrap(kek, contentKey),\r\n options.recipients ?? []);\r\n\r\n }\r\n\r\n\r\n // ------------------------------------------------------------ recovering\r\n\r\n /**\r\n * The content key this recipient carries, or null when the given key is\r\n * not the one it was built for.\r\n *\r\n * Null rather than an exception, and rather than a reason: a party holding\r\n * several keys tries them in turn, and \"not this one\" is the ordinary\r\n * answer rather than an error. For key wrap it is also the *only* honest\r\n * answer — RFC 3394's integrity check is what distinguishes a wrong key\r\n * from a right one, and saying more about which would say something about\r\n * the key.\r\n */\r\n public contentKey(key: CoseKey): Uint8Array | null {\r\n\r\n const algorithm = this.algorithm;\r\n\r\n if (algorithm === null)\r\n return null;\r\n\r\n if (key.keyType !== KEY_TYPE_SYMMETRIC)\r\n return null;\r\n\r\n if (algorithm.family === 'direct') {\r\n\r\n // \"When this algorithm is used, the 'protected' field MUST be zero\r\n // length\" [RFC 9053, §6.1.1] — and a non-empty ciphertext would be\r\n // key material this route is not supposed to carry.\r\n if (this.protectedHeaderBytes.length !== 0 || this.ciphertext.length !== 0)\r\n return null;\r\n\r\n return key.privateKeyBytes();\r\n\r\n }\r\n\r\n if (algorithm.family === 'keywrap')\r\n return aesKeyUnwrap(key.privateKeyBytes(), this.ciphertext);\r\n\r\n return null;\r\n\r\n }\r\n\r\n\r\n // --------------------------------------------------------- serialization\r\n\r\n /** Read a COSE_recipient. */\r\n public static parse(value: CborValue): CoseRecipient {\r\n\r\n if (value.type !== 'array')\r\n throw new CoseError(`A COSE_recipient must be a CBOR array, but was a CBOR ${value.type}!`);\r\n\r\n if (value.items.length !== 3 && value.items.length !== 4)\r\n throw new CoseError(`A COSE_recipient must be a CBOR array of 3 or 4 elements, but had ${String(value.items.length)} element(s)!`);\r\n\r\n const [protectedBytes, unprotected, ciphertext, nested] = value.items;\r\n\r\n if (protectedBytes?.type !== 'bytes')\r\n throw new CoseError('The protected header bucket of a COSE_recipient must be a byte string!');\r\n\r\n if (unprotected === undefined)\r\n throw new CoseError('A COSE_recipient must carry an unprotected header bucket!');\r\n\r\n if (ciphertext === undefined || (ciphertext.type !== 'bytes' && ciphertext.type !== 'null'))\r\n throw new CoseError('The ciphertext of a COSE_recipient must be a byte string, or null!');\r\n\r\n let recipients: CoseRecipient[] = [];\r\n\r\n if (nested !== undefined) {\r\n\r\n if (nested.type !== 'array' || nested.items.length === 0)\r\n throw new CoseError('The nested recipients of a COSE_recipient must be a non-empty CBOR array!');\r\n\r\n recipients = nested.items.map(each => CoseRecipient.parse(each));\r\n\r\n }\r\n\r\n return new CoseRecipient(protectedBytes.value,\r\n CoseHeaders.parse(unprotected),\r\n ciphertext.type === 'bytes' ? ciphertext.value : NO_BYTES,\r\n recipients);\r\n\r\n }\r\n\r\n\r\n /** The CBOR form of this recipient. */\r\n public toCbor(): CborValue {\r\n\r\n const items = [cbor.bytes(this.protectedHeaderBytes),\r\n this.unprotectedHeader.toCbor(),\r\n cbor.bytes(this.ciphertext)];\r\n\r\n if (this.recipients.length > 0)\r\n items.push(cbor.array(this.recipients.map(each => each.toCbor())));\r\n\r\n return cbor.array(items);\r\n\r\n }\r\n\r\n\r\n public toString(): string {\r\n return `${this.algorithm?.name ?? 'unknown'} recipient, ${String(this.ciphertext.length)} bytes`;\r\n }\r\n\r\n}\r\n\r\n\r\n/** The key-wrap algorithm a key-encryption key of the given width belongs to. */\r\nexport function keyWrapAlgorithmFor(keySize: number): CoseAlgorithm {\r\n\r\n switch (keySize) {\r\n case 16: return CoseAlgorithms.A128KW;\r\n case 24: return CoseAlgorithms.A192KW;\r\n case 32: return CoseAlgorithms.A256KW;\r\n }\r\n\r\n throw new CoseError(`AES key wrap needs a key-encryption key of 16, 24 or 32 bytes, but a ${String(keySize)}-byte key was given!`);\r\n\r\n}\r\n\r\n\r\nfunction requireSymmetric(key: CoseKey, what: string): void {\r\n\r\n if (key.keyType !== KEY_TYPE_SYMMETRIC)\r\n throw new CoseError(`${what} needs a COSE key of key type Symmetric, but a key of key type ${String(key.keyType)} was given!`);\r\n\r\n}\r\n\r\n\r\n/**\r\n * The unprotected bucket of a recipient: its algorithm, and its key identifier\r\n * when there is one.\r\n *\r\n * Both live in the *unprotected* bucket, which is what the published examples\r\n * do and what `direct` requires — its protected bucket must be zero length, so\r\n * there is nowhere else for the algorithm to go.\r\n */\r\nfunction headersFor(algorithm: CoseAlgorithm, keyIdentifier: Uint8Array | null): CoseHeaders {\r\n\r\n const parameters: CborEntry[] = [\r\n [label(HeaderLabel.algorithm), algorithmToCbor(algorithm)],\r\n ];\r\n\r\n if (keyIdentifier !== null)\r\n parameters.push([label(HeaderLabel.keyIdentifier), cbor.bytes(keyIdentifier)]);\r\n\r\n return new CoseHeaders(parameters);\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * A COSE_Mac message [RFC 9052, Section 6.1]: a payload authenticated with a\r\n * content key that the message itself delivers to each recipient. CBOR tag 97.\r\n *\r\n * ```\r\n * COSE_Mac = [ Headers, payload : bstr / nil, tag : bstr, recipients : [+COSE_recipient] ]\r\n * ```\r\n *\r\n * Five elements where `COSE_Mac0` has four, and the fifth is the whole point:\r\n * `COSE_Mac0` assumes both parties already hold the key, while this solves the\r\n * distribution problem inside the message. The `MAC_structure` is the same\r\n * four-element structure either way, differing only in its context string —\r\n * `\"MAC\"` here, `\"MAC0\"` there.\r\n *\r\n * **A recipient list costs more than bytes.** Every recipient holds the same\r\n * content key, so with more than one of them the tag stops distinguishing them\r\n * at all: any recipient can produce a message the others will accept as coming\r\n * from the sender. A `COSE_Mac0` between two parties at least tells each of\r\n * them that the other made it, on the grounds that they did not make it\r\n * themselves; a `COSE_Mac` to three parties tells nobody anything of the kind.\r\n * RFC 9052 §8.2 states it outright — a MAC provides *\"either no or very limited\r\n * data origination\"* and *\"cannot be used to prove the identity of the sender\r\n * to a third party\"*.\r\n *\r\n * That is worth having in view before reaching for this structure. What it is\r\n * genuinely good at is cheap integrity for a group that already trusts one\r\n * another jointly — and if the question is who within that group said\r\n * something, the answer has to be a signature.\r\n *\r\n * The single-`direct`-recipient case is `COSE_Mac0` with extra ceremony: the\r\n * recipient structure carries an empty protected bucket, an empty ciphertext\r\n * and a key identifier, and nothing else. RFC 9052's Appendix C.5.1 is exactly\r\n * that, and it is why `COSE_Mac0` exists.\r\n */\r\n\r\nimport { macWith, verifyMacWith } from './algorithm.ts';\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport { bytesEqual, cbor, decode,\r\n encode, NO_BYTES } from './cbor.ts';\r\nimport type { CborValue } from './cbor.ts';\r\nimport { CoseError, notVerified, VERIFIED } from './errors.ts';\r\nimport type { Verification } from './errors.ts';\r\nimport { CoseHeaders,\r\n verifyCriticalHeaderParameters } from './headers.ts';\r\nimport { KEY_TYPE_SYMMETRIC } from './key.ts';\r\nimport type { CoseKey } from './key.ts';\r\nimport { HeaderLabel, label } from './labels.ts';\r\nimport { canonicalizePayload } from './payload.ts';\r\nimport { CoseRecipient } from './recipient.ts';\r\nimport { resolveAlgorithm, resolvePayload } from './resolve.ts';\r\n\r\n\r\n/** The CBOR tag of a COSE_Mac message. */\r\nexport const COSE_MAC_TAG = 97;\r\n\r\n/** The context string of a COSE_Mac authentication tag [RFC 9052, Section 6.3]. */\r\nexport const MAC_CONTEXT = 'MAC';\r\n\r\n\r\n/** What a party authenticating may choose. */\r\nexport interface MacOptions {\r\n\r\n /** Data authenticated along with the payload without travelling in the message. */\r\n readonly externalAad?: Uint8Array | null;\r\n\r\n /** Whether to omit the payload from the message. */\r\n readonly detachPayload?: boolean;\r\n\r\n /**\r\n * Whether to rewrite a CBOR payload in the deterministic encoding of\r\n * RFC 8949 §4.2.1 before authenticating it, so that a receiver who parses\r\n * and re-serializes the record arrives at the very bytes this tag covers.\r\n * Defaults to true. A payload that is not CBOR is authenticated as it is.\r\n */\r\n readonly canonicalizePayload?: boolean;\r\n\r\n\r\n /** Whether to wrap the message within CBOR tag 97. Defaults to true. */\r\n readonly tagged?: boolean;\r\n\r\n}\r\n\r\n\r\n/** What a party checking may have to supply. */\r\nexport interface MacVerifyOptions {\r\n\r\n /** The data that was authenticated along with the payload. */\r\n readonly externalAad?: Uint8Array | null;\r\n\r\n /** The payload, when the message carries a detached one. */\r\n readonly detachedPayload?: Uint8Array | null;\r\n\r\n /** The algorithm the caller expects. */\r\n readonly expectedAlgorithm?: CoseAlgorithm | null;\r\n\r\n /** Header parameters the caller processes itself. */\r\n readonly alsoUnderstood?: readonly CborValue[];\r\n\r\n}\r\n\r\n\r\nexport class CoseMac {\r\n\r\n /** The serialized protected bucket, exactly as authenticated and received. */\r\n public readonly protectedHeaderBytes: Uint8Array;\r\n\r\n /** The protected header parameters, which the authentication tag covers. */\r\n public readonly protectedHeader: CoseHeaders;\r\n\r\n /** The unprotected header parameters, which it does not. */\r\n public readonly unprotectedHeader: CoseHeaders;\r\n\r\n /** The authenticated payload, or null when it is detached. */\r\n public readonly payload: Uint8Array | null;\r\n\r\n /** The authentication tag — not the CBOR tag. */\r\n public readonly tag: Uint8Array;\r\n\r\n /** How the content key reaches each party. */\r\n public readonly recipients: readonly CoseRecipient[];\r\n\r\n /** Whether this message is wrapped within CBOR tag 97. */\r\n public readonly isTagged: boolean;\r\n\r\n\r\n public constructor(protectedHeaderBytes: Uint8Array,\r\n unprotectedHeader: CoseHeaders | null,\r\n payload: Uint8Array | null,\r\n tag: Uint8Array,\r\n recipients: readonly CoseRecipient[],\r\n isTagged = true) {\r\n\r\n if (recipients.length === 0)\r\n throw new CoseError('A COSE_Mac message must carry at least one recipient!');\r\n\r\n this.protectedHeaderBytes = protectedHeaderBytes;\r\n this.protectedHeader = CoseHeaders.parseProtected(protectedHeaderBytes);\r\n this.unprotectedHeader = unprotectedHeader ?? CoseHeaders.empty;\r\n this.payload = payload;\r\n this.tag = tag;\r\n this.recipients = [...recipients];\r\n this.isTagged = isTagged;\r\n\r\n }\r\n\r\n\r\n /** Whether the payload is detached. */\r\n public get isDetached(): boolean {\r\n return this.payload === null;\r\n }\r\n\r\n /** The MAC algorithm, protected bucket first. */\r\n public get algorithm(): CoseAlgorithm | null {\r\n return this.protectedHeader.algorithm ?? this.unprotectedHeader.algorithm;\r\n }\r\n\r\n\r\n /**\r\n * The encoded MAC_structure [RFC 9052, Section 6.3] with the `\"MAC\"`\r\n * context — the one difference from a COSE_Mac0's.\r\n */\r\n public static toBeMaced(protectedHeaderBytes: Uint8Array,\r\n payload: Uint8Array,\r\n externalAad: Uint8Array | null = null): Uint8Array {\r\n\r\n return encode(cbor.array([\r\n cbor.text(MAC_CONTEXT),\r\n cbor.bytes(protectedHeaderBytes),\r\n cbor.bytes(externalAad ?? NO_BYTES),\r\n cbor.bytes(payload),\r\n ]));\r\n\r\n }\r\n\r\n\r\n /** The encoded MAC_structure of this message. */\r\n public toBeMaced(options: { externalAad?: Uint8Array | null;\r\n detachedPayload?: Uint8Array | null } = {}): Uint8Array {\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Mac message');\r\n\r\n if (!payload.ok)\r\n throw new CoseError(payload.reason);\r\n\r\n return CoseMac.toBeMaced(this.protectedHeaderBytes,\r\n payload.value,\r\n options.externalAad ?? null);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Authenticate a payload under a content key, and deliver that key to each\r\n * recipient.\r\n *\r\n * The content key is the caller's rather than generated here, for the same\r\n * reason as everywhere else in this package: a generated one would make the\r\n * message unreproducible, and whoever has a key management scheme has it\r\n * for a reason.\r\n */\r\n public static create(payload: Uint8Array,\r\n contentKey: CoseKey,\r\n recipients: readonly CoseRecipient[],\r\n options: MacOptions = {}): CoseMac {\r\n\r\n const algorithm = contentKey.algorithm\r\n ?? (() => { throw new CoseError('A COSE_Mac message needs a MAC algorithm on its content key!'); })();\r\n\r\n if (algorithm.family !== 'hmac')\r\n throw new CoseError(`The COSE algorithm '${algorithm.name}' is not a message authentication algorithm!`);\r\n\r\n if (contentKey.keyType !== KEY_TYPE_SYMMETRIC)\r\n throw new CoseError(`A COSE_Mac message needs a content key of key type Symmetric, but a key of key type ${String(contentKey.keyType)} was given!`);\r\n\r\n const protectedHeader = new CoseHeaders([\r\n [label(HeaderLabel.algorithm), cbor.int(algorithm.id)],\r\n ]);\r\n\r\n const protectedBytes = protectedHeader.toProtectedBytes();\r\n\r\n // A MAC dies the same death as a signature: a receiver that decodes\r\n // the payload and encodes it again produces the deterministic\r\n // spelling, and a tag over another one no longer verifies. A detached\r\n // payload is the caller's to transmit, so rewriting it here would\r\n // authenticate bytes nobody holds.\r\n const authenticated = options.canonicalizePayload === false\r\n ? payload\r\n : canonicalizePayload(payload);\r\n\r\n if (options.detachPayload === true && !bytesEqual(authenticated, payload))\r\n throw new CoseError('The payload of this COSE_Mac message is detached, so canonicalizing it here would authenticate bytes that nobody holds: canonicalize the payload yourself (canonicalizePayload), authenticate and transmit those, or pass canonicalizePayload: false to authenticate the payload exactly as it is!');\r\n\r\n const tag = macWith(algorithm,\r\n CoseMac.toBeMaced(protectedBytes, authenticated, options.externalAad ?? null),\r\n contentKey.privateKeyBytes());\r\n\r\n return new CoseMac(protectedBytes,\r\n null,\r\n options.detachPayload === true ? null : authenticated,\r\n tag,\r\n recipients,\r\n options.tagged ?? true);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Verify this message with a key one of its recipients was built for.\r\n *\r\n * Every recipient is tried, because a party holding one key does not\r\n * generally know which entry in the list is theirs.\r\n */\r\n public verify(key: CoseKey, options: MacVerifyOptions = {}): Verification {\r\n\r\n const critical = verifyCriticalHeaderParameters(this.protectedHeader,\r\n this.unprotectedHeader,\r\n options.alsoUnderstood ?? []);\r\n\r\n if (!critical.verified)\r\n return critical;\r\n\r\n const algorithm = resolveAlgorithm(this.protectedHeader,\r\n this.unprotectedHeader,\r\n options.expectedAlgorithm ?? null,\r\n 'This COSE_Mac message');\r\n\r\n if (!algorithm.ok)\r\n return notVerified(algorithm.reason);\r\n\r\n if (algorithm.value.family !== 'hmac')\r\n return notVerified(`The COSE algorithm '${algorithm.value.name}' is not a message authentication algorithm: a COSE_Mac message can not be authenticated with a signature algorithm!`);\r\n\r\n const payload = resolvePayload(this.payload,\r\n options.detachedPayload ?? null,\r\n 'this COSE_Mac message');\r\n\r\n if (!payload.ok)\r\n return notVerified(payload.reason);\r\n\r\n if (key.keyType !== KEY_TYPE_SYMMETRIC)\r\n return notVerified(`A COSE_Mac message needs a key of key type Symmetric, but a key of key type ${String(key.keyType)} was given!`);\r\n\r\n const toBeMaced = CoseMac.toBeMaced(this.protectedHeaderBytes,\r\n payload.value,\r\n options.externalAad ?? null);\r\n\r\n let tried = 0;\r\n\r\n for (const recipient of this.recipients) {\r\n\r\n const contentKey = recipient.contentKey(key);\r\n\r\n if (contentKey === null)\r\n continue;\r\n\r\n tried++;\r\n\r\n try {\r\n if (verifyMacWith(algorithm.value, toBeMaced, this.tag, contentKey))\r\n return VERIFIED;\r\n }\r\n catch {\r\n // A content key of the wrong width for this algorithm is\r\n // somebody else's recipient rather than a failure of ours.\r\n continue;\r\n }\r\n\r\n }\r\n\r\n return notVerified(tried === 0\r\n ? 'None of the recipients of this COSE_Mac message yielded a content key for the given key!'\r\n : 'A recipient yielded a content key, and the authentication tag is not the right one under it!');\r\n\r\n }\r\n\r\n\r\n // --------------------------------------------------------- serialization\r\n\r\n /** Read a COSE_Mac message, tagged or not. */\r\n public static parse(input: Uint8Array | CborValue): CoseMac {\r\n\r\n const value = input instanceof Uint8Array ? decode(input) : input;\r\n\r\n let isTagged = false;\r\n let message = value;\r\n\r\n if (message.type === 'tag') {\r\n\r\n if (message.tag !== BigInt(COSE_MAC_TAG))\r\n throw new CoseError(`A COSE_Mac message must be tagged with CBOR tag ${String(COSE_MAC_TAG)}, but was tagged with CBOR tag ${String(message.tag)}!`);\r\n\r\n isTagged = true;\r\n message = message.value;\r\n\r\n }\r\n\r\n if (message.type !== 'array')\r\n throw new CoseError(`A COSE_Mac message must be a CBOR array, but was a CBOR ${message.type}!`);\r\n\r\n if (message.items.length !== 5)\r\n throw new CoseError(`A COSE_Mac message must be a CBOR array of 5 elements, but had ${String(message.items.length)} element(s)!`);\r\n\r\n const [protectedBytes, unprotected, payload, tag, recipients] = message.items;\r\n\r\n if (protectedBytes?.type !== 'bytes')\r\n throw new CoseError('The protected header bucket of a COSE_Mac message must be a byte string!');\r\n\r\n if (unprotected === undefined)\r\n throw new CoseError('A COSE_Mac message must carry an unprotected header bucket!');\r\n\r\n if (payload === undefined || (payload.type !== 'null' && payload.type !== 'bytes'))\r\n throw new CoseError('The payload of a COSE_Mac message must be a byte string, or null when it is detached!');\r\n\r\n if (tag?.type !== 'bytes')\r\n throw new CoseError('The authentication tag of a COSE_Mac message must be a byte string!');\r\n\r\n if (recipients?.type !== 'array' || recipients.items.length === 0)\r\n throw new CoseError('A COSE_Mac message must carry a non-empty array of recipients!');\r\n\r\n return new CoseMac(protectedBytes.value,\r\n CoseHeaders.parse(unprotected),\r\n payload.type === 'bytes' ? payload.value : null,\r\n tag.value,\r\n recipients.items.map(each => CoseRecipient.parse(each)),\r\n isTagged);\r\n\r\n }\r\n\r\n\r\n /** The CBOR form of this message. */\r\n public toCbor(): CborValue {\r\n\r\n const message = cbor.array([\r\n cbor.bytes(this.protectedHeaderBytes),\r\n this.unprotectedHeader.toCbor(),\r\n this.payload !== null ? cbor.bytes(this.payload) : cbor.nullValue,\r\n cbor.bytes(this.tag),\r\n cbor.array(this.recipients.map(each => each.toCbor())),\r\n ]);\r\n\r\n return this.isTagged ? cbor.tag(COSE_MAC_TAG, message) : message;\r\n\r\n }\r\n\r\n\r\n /** The CBOR encoding of this message. */\r\n public toBytes(): Uint8Array {\r\n return encode(this.toCbor());\r\n }\r\n\r\n\r\n public toString(): string {\r\n return `COSE_Mac${this.algorithm !== null ? ` ${this.algorithm.name}` : ''}, ${String(this.recipients.length)} recipient(s)`;\r\n }\r\n\r\n}\r\n","/*\r\n * Copyright (c) 2026 GraphDefined GmbH <achim.friedland@graphdefined.com>\r\n * This file is part of Vanaheimr COSE <https://github.com/Vanaheimr/COSE.TS>\r\n * SPDX-License-Identifier: Apache-2.0\r\n */\r\n\r\n/**\r\n * The encrypted COSE structures [RFC 9052, Section 5]: `COSE_Encrypt0`\r\n * (CBOR tag 16) and `COSE_Encrypt` (CBOR tag 96), with AES-GCM.\r\n *\r\n * ```\r\n * COSE_Encrypt0 = [ Headers, ciphertext : bstr / nil ]\r\n * COSE_Encrypt = [ Headers, ciphertext : bstr / nil, recipients : [+COSE_recipient] ]\r\n * ```\r\n *\r\n * Three things about these differ from everything else in this package, and\r\n * all three catch people out.\r\n *\r\n * **The `Enc_structure` has three elements, not four.** It is\r\n * `[context, protected, external_aad]` — no payload. That is not an oversight:\r\n * the payload is what is being *encrypted*, and the `Enc_structure` is what is\r\n * merely *authenticated* alongside it. It becomes the AEAD's additional data,\r\n * so the recipient rebuilds it from the message rather than receiving it.\r\n *\r\n * **The authentication tag is not a field.** AES-GCM's 16-byte tag is appended\r\n * to the ciphertext and travels inside the same byte string. An implementation\r\n * giving it a field of its own interoperates with nothing.\r\n *\r\n * **The nonce is public and must never repeat.** It travels in the `iv` header\r\n * parameter, in the clear, and that is fine — what is not fine is using one\r\n * twice with the same key. GCM fails catastrophically on nonce reuse: two\r\n * messages under one nonce leak the XOR of their plaintexts *and* the\r\n * authentication subkey, which lets an attacker forge afterwards. The nonce is\r\n * therefore never generated here. The caller passes it, because only the\r\n * caller knows whether it has been used before.\r\n *\r\n * And the point worth keeping in view: an encrypted message says nothing about\r\n * *who* sent it. AEAD integrity means \"whoever holds this key wrote this\",\r\n * which with several recipients means any of them. RFC 9052 §8.3 says as much:\r\n * content encryption provides *\"either no or very limited data origination\"*.\r\n * A signed payload inside an encrypted envelope is how one gets both.\r\n */\r\n\r\nimport { aesGcmDecrypt, aesGcmEncrypt,\r\n GCM_NONCE_SIZE } from './aes.ts';\r\nimport { algorithmToCbor } from './algorithm.ts';\r\nimport type { CoseAlgorithm } from './algorithm.ts';\r\nimport { cbor, decode, encode, NO_BYTES } from './cbor.ts';\r\nimport type { CborEntry, CborValue } from './cbor.ts';\r\nimport { CoseError, notDecrypted } from './errors.ts';\r\nimport type { Decryption } from './errors.ts';\r\nimport { CoseHeaders,\r\n verifyCriticalHeaderParameters } from './headers.ts';\r\nimport { KEY_TYPE_SYMMETRIC } from './key.ts';\r\nimport type { CoseKey } from './key.ts';\r\nimport { HeaderLabel, label } from './labels.ts';\r\nimport { CoseRecipient } from './recipient.ts';\r\n\r\n\r\n/** The CBOR tag of a COSE_Encrypt0 message. */\r\nexport const COSE_ENCRYPT0_TAG = 16;\r\n\r\n/** The CBOR tag of a COSE_Encrypt message. */\r\nexport const COSE_ENCRYPT_TAG = 96;\r\n\r\n/** The context string of a COSE_Encrypt0 [RFC 9052, Section 5.3]. */\r\nexport const ENCRYPT0_CONTEXT = 'Encrypt0';\r\n\r\n/** The context string of the body of a COSE_Encrypt. */\r\nexport const ENCRYPT_CONTEXT = 'Encrypt';\r\n\r\n\r\n/**\r\n * The encoded `Enc_structure` [RFC 9052, Section 5.3]:\r\n *\r\n * ```\r\n * Enc_structure = [ context, protected : empty_or_serialized_map, external_aad : bstr ]\r\n * ```\r\n */\r\nexport function encStructure(context: string,\r\n protectedHeaderBytes: Uint8Array,\r\n externalAad: Uint8Array | null = null): Uint8Array {\r\n\r\n return encode(cbor.array([\r\n cbor.text(context),\r\n cbor.bytes(protectedHeaderBytes),\r\n cbor.bytes(externalAad ?? NO_BYTES),\r\n ]));\r\n\r\n}\r\n\r\n\r\n/** What a party encrypting may choose. */\r\nexport interface EncryptOptions {\r\n\r\n /**\r\n * The nonce, which is required.\r\n *\r\n * There is no default and there will not be one. A nonce reused with the\r\n * same key breaks AES-GCM outright, and this package has no way of knowing\r\n * which nonces a caller has already spent.\r\n */\r\n readonly iv: Uint8Array;\r\n\r\n /** A key identifier for the unprotected bucket, defaulting to the key's own. */\r\n readonly keyIdentifier?: Uint8Array | null;\r\n\r\n /** Data authenticated along with the payload without travelling in the message. */\r\n readonly externalAad?: Uint8Array | null;\r\n\r\n /** Whether to omit the ciphertext from the message. */\r\n readonly detachPayload?: boolean;\r\n\r\n /** Whether to wrap the message within its CBOR tag. Defaults to true. */\r\n readonly tagged?: boolean;\r\n\r\n}\r\n\r\n\r\n/** What a party decrypting may have to supply. */\r\nexport interface DecryptOptions {\r\n\r\n /** The data that was authenticated along with the payload. */\r\n readonly externalAad?: Uint8Array | null;\r\n\r\n /** The ciphertext, when the message carries a detached one. */\r\n readonly detachedCiphertext?: Uint8Array | null;\r\n\r\n /** The algorithm the caller expects. */\r\n readonly expectedAlgorithm?: CoseAlgorithm | null;\r\n\r\n /** Header parameters the caller processes itself. */\r\n readonly alsoUnderstood?: readonly CborValue[];\r\n\r\n}\r\n\r\n\r\n/** Everything the two encrypted structures share. */\r\nabstract class CoseEncryptedBase {\r\n\r\n /** The serialized protected bucket, exactly as authenticated and received. */\r\n public readonly protectedHeaderBytes: Uint8Array;\r\n\r\n /** The protected header parameters, which the AEAD tag covers. */\r\n public readonly protectedHeader: CoseHeaders;\r\n\r\n /** The unprotected header parameters, which it does not. */\r\n public readonly unprotectedHeader: CoseHeaders;\r\n\r\n /** The ciphertext with the AEAD tag appended, or null when detached. */\r\n public readonly ciphertext: Uint8Array | null;\r\n\r\n /** Whether this message is wrapped within its CBOR tag. */\r\n public readonly isTagged: boolean;\r\n\r\n\r\n protected constructor(protectedHeaderBytes: Uint8Array,\r\n unprotectedHeader: CoseHeaders | null,\r\n ciphertext: Uint8Array | null,\r\n isTagged: boolean) {\r\n\r\n this.protectedHeaderBytes = protectedHeaderBytes;\r\n this.protectedHeader = CoseHeaders.parseProtected(protectedHeaderBytes);\r\n this.unprotectedHeader = unprotectedHeader ?? CoseHeaders.empty;\r\n this.ciphertext = ciphertext;\r\n this.isTagged = isTagged;\r\n\r\n }\r\n\r\n\r\n /** The content encryption algorithm, protected bucket first. */\r\n public get algorithm(): CoseAlgorithm | null {\r\n return this.protectedHeader.algorithm ?? this.unprotectedHeader.algorithm;\r\n }\r\n\r\n /** The key identifier, protected bucket first. */\r\n public get keyIdentifier(): Uint8Array | null {\r\n return this.protectedHeader.keyIdentifier ?? this.unprotectedHeader.keyIdentifier;\r\n }\r\n\r\n /** The nonce, from either bucket. It travels in the clear and must never repeat. */\r\n public get iv(): Uint8Array | null {\r\n\r\n const value = this.protectedHeader.get(label(HeaderLabel.iv)) ??\r\n this.unprotectedHeader.get(label(HeaderLabel.iv));\r\n\r\n if (value === null)\r\n return null;\r\n\r\n if (value.type !== 'bytes')\r\n throw new CoseError('The initialization vector of a COSE message must be a byte string!');\r\n\r\n return value.value;\r\n\r\n }\r\n\r\n /** Whether the ciphertext is detached. */\r\n public get isDetached(): boolean {\r\n return this.ciphertext === null;\r\n }\r\n\r\n\r\n /**\r\n * Decrypt with a content encryption key that has already been established.\r\n *\r\n * The shared half of both structures: `COSE_Encrypt0` uses it with the key\r\n * the caller passed, `COSE_Encrypt` with the one a recipient yielded.\r\n */\r\n protected decryptWith(contentKey: Uint8Array,\r\n context: string,\r\n options: DecryptOptions): Decryption {\r\n\r\n const critical = verifyCriticalHeaderParameters(this.protectedHeader,\r\n this.unprotectedHeader,\r\n options.alsoUnderstood ?? []);\r\n\r\n if (!critical.verified)\r\n return notDecrypted(critical.reason);\r\n\r\n const algorithm = options.expectedAlgorithm ?? this.protectedHeader.algorithm\r\n ?? this.unprotectedHeader.algorithm;\r\n\r\n if (algorithm === null)\r\n return notDecrypted('This COSE message does not state its content encryption algorithm: pass the expected algorithm explicitly!');\r\n\r\n const stated = this.algorithm;\r\n\r\n if (stated !== null && stated.id !== algorithm.id)\r\n return notDecrypted(`This COSE message was encrypted with the algorithm '${stated.name}', but the algorithm '${algorithm.name}' was expected!`);\r\n\r\n if (algorithm.family !== 'aesgcm')\r\n return notDecrypted(`The COSE algorithm '${algorithm.name}' is not a content encryption algorithm this implementation supports!`);\r\n\r\n if (algorithm.keySize !== null && contentKey.length !== algorithm.keySize)\r\n return notDecrypted(`The algorithm '${algorithm.name}' needs a ${String(algorithm.keySize)}-byte key, but the content key is ${String(contentKey.length)} bytes long!`);\r\n\r\n let nonce: Uint8Array | null;\r\n\r\n try {\r\n nonce = this.iv;\r\n }\r\n catch (exception) {\r\n return notDecrypted(exception instanceof Error ? exception.message : String(exception));\r\n }\r\n\r\n if (nonce === null)\r\n return notDecrypted('This COSE message carries no initialization vector!');\r\n\r\n if (nonce.length !== GCM_NONCE_SIZE)\r\n return notDecrypted(`AES-GCM within COSE uses a ${String(GCM_NONCE_SIZE)}-byte nonce, but this message carries a ${String(nonce.length)}-byte one!`);\r\n\r\n const carried = this.ciphertext;\r\n const given = options.detachedCiphertext ?? null;\r\n\r\n if (carried !== null && given !== null)\r\n return notDecrypted('This COSE message carries its ciphertext, and a detached ciphertext was supplied as well!');\r\n\r\n const body = carried ?? given;\r\n\r\n if (body === null)\r\n return notDecrypted('This COSE message carries a detached ciphertext, which has to be supplied in order to decrypt it!');\r\n\r\n const plaintext = aesGcmDecrypt(contentKey, nonce, body,\r\n encStructure(context,\r\n this.protectedHeaderBytes,\r\n options.externalAad ?? null));\r\n\r\n return plaintext === null\r\n ? notDecrypted('The ciphertext does not authenticate under this key: it was altered, or the key, the nonce or the additional data is not the right one!')\r\n : { decrypted: true, plaintext };\r\n\r\n }\r\n\r\n}\r\n\r\n\r\n/**\r\n * A COSE_Encrypt0 message: encrypted for a recipient who already holds the key.\r\n */\r\nexport class CoseEncrypt0 extends CoseEncryptedBase {\r\n\r\n public constructor(protectedHeaderBytes: Uint8Array,\r\n unprotectedHeader: CoseHeaders | null,\r\n ciphertext: Uint8Array | null,\r\n isTagged = true) {\r\n super(protectedHeaderBytes, unprotectedHeader, ciphertext, isTagged);\r\n }\r\n\r\n\r\n /** The encoded Enc_structure of this message. */\r\n public toBeEncrypted(externalAad: Uint8Array | null = null): Uint8Array {\r\n return encStructure(ENCRYPT0_CONTEXT, this.protectedHeaderBytes, externalAad);\r\n }\r\n\r\n\r\n /** Encrypt a payload, with the algorithm in the protected bucket. */\r\n public static encrypt(plaintext: Uint8Array,\r\n key: CoseKey,\r\n options: EncryptOptions): CoseEncrypt0 {\r\n\r\n const algorithm = requireAesGcm(key);\r\n\r\n const keyIdentifier = options.keyIdentifier === undefined\r\n ? key.keyIdentifier\r\n : options.keyIdentifier;\r\n\r\n const unprotected: CborEntry[] = [[label(HeaderLabel.iv), cbor.bytes(options.iv)]];\r\n\r\n if (keyIdentifier !== null)\r\n unprotected.push([label(HeaderLabel.keyIdentifier), cbor.bytes(keyIdentifier)]);\r\n\r\n return CoseEncrypt0.encryptWithHeaders(\r\n plaintext, key,\r\n new CoseHeaders([[label(HeaderLabel.algorithm), algorithmToCbor(algorithm)]]),\r\n new CoseHeaders(unprotected),\r\n options);\r\n\r\n }\r\n\r\n\r\n /** Encrypt a payload with header buckets the caller composed. */\r\n public static encryptWithHeaders(plaintext: Uint8Array,\r\n key: CoseKey,\r\n protectedHeader: CoseHeaders,\r\n unprotectedHeader: CoseHeaders | null,\r\n options: EncryptOptions): CoseEncrypt0 {\r\n\r\n const algorithm = protectedHeader.algorithm ?? requireAesGcm(key);\r\n\r\n requireUsable(key, algorithm);\r\n\r\n const protectedBytes = protectedHeader.toProtectedBytes();\r\n\r\n const ciphertext = aesGcmEncrypt(key.privateKeyBytes(),\r\n options.iv,\r\n plaintext,\r\n encStructure(ENCRYPT0_CONTEXT, protectedBytes,\r\n options.externalAad ?? null));\r\n\r\n return new CoseEncrypt0(protectedBytes,\r\n unprotectedHeader,\r\n options.detachPayload === true ? null : ciphertext,\r\n options.tagged ?? true);\r\n\r\n }\r\n\r\n\r\n /** Decrypt this message with the key it was encrypted for. */\r\n public decrypt(key: CoseKey, options: DecryptOptions = {}): Decryption {\r\n\r\n if (key.keyType !== KEY_TYPE_SYMMETRIC)\r\n return notDecrypted(`A COSE_Encrypt0 message needs a key of key type Symmetric, but a key of key type ${String(key.keyType)} was given!`);\r\n\r\n return this.decryptWith(key.privateKeyBytes(), ENCRYPT0_CONTEXT, options);\r\n\r\n }\r\n\r\n\r\n /** Read a COSE_Encrypt0 message, tagged or not. */\r\n public static parse(input: Uint8Array | CborValue): CoseEncrypt0 {\r\n\r\n const { isTagged, items } = untag(input, COSE_ENCRYPT0_TAG, 3, 'COSE_Encrypt0');\r\n\r\n const [protectedBytes, unprotected, ciphertext] = items;\r\n\r\n return new CoseEncrypt0(bytesOfProtected(protectedBytes, 'COSE_Encrypt0'),\r\n CoseHeaders.parse(unprotected!),\r\n ciphertextOf(ciphertext!, 'COSE_Encrypt0'),\r\n isTagged);\r\n\r\n }\r\n\r\n\r\n /** The CBOR form of this message. */\r\n public toCbor(): CborValue {\r\n\r\n const message = cbor.array([\r\n cbor.bytes(this.protectedHeaderBytes),\r\n this.unprotectedHeader.toCbor(),\r\n this.ciphertext !== null ? cbor.bytes(this.ciphertext) : cbor.nullValue,\r\n ]);\r\n\r\n return this.isTagged ? cbor.tag(COSE_ENCRYPT0_TAG, message) : message;\r\n\r\n }\r\n\r\n\r\n /** The CBOR encoding of this message. */\r\n public toBytes(): Uint8Array {\r\n return encode(this.toCbor());\r\n }\r\n\r\n\r\n public toString(): string {\r\n return `COSE_Encrypt0${this.algorithm !== null ? ` ${this.algorithm.name}` : ''}, ${String(this.ciphertext?.length ?? 0)} bytes`;\r\n }\r\n\r\n}\r\n\r\n\r\n/**\r\n * A COSE_Encrypt message: encrypted once, with the content key delivered to\r\n * each recipient in a structure of its own.\r\n */\r\nexport class CoseEncrypt extends CoseEncryptedBase {\r\n\r\n /** How the content key reaches each party. */\r\n public readonly recipients: readonly CoseRecipient[];\r\n\r\n\r\n public constructor(protectedHeaderBytes: Uint8Array,\r\n unprotectedHeader: CoseHeaders | null,\r\n ciphertext: Uint8Array | null,\r\n recipients: readonly CoseRecipient[],\r\n isTagged = true) {\r\n\r\n super(protectedHeaderBytes, unprotectedHeader, ciphertext, isTagged);\r\n\r\n if (recipients.length === 0)\r\n throw new CoseError('A COSE_Encrypt message must carry at least one recipient!');\r\n\r\n this.recipients = [...recipients];\r\n\r\n }\r\n\r\n\r\n /** The encoded Enc_structure of this message. */\r\n public toBeEncrypted(externalAad: Uint8Array | null = null): Uint8Array {\r\n return encStructure(ENCRYPT_CONTEXT, this.protectedHeaderBytes, externalAad);\r\n }\r\n\r\n\r\n /**\r\n * Encrypt a payload under a content key, and deliver that key to each\r\n * recipient.\r\n *\r\n * The content key is the caller's, not this method's, for the same reason\r\n * the nonce is: generating one here would make the message\r\n * unreproducible, and a caller who has a key management scheme has one for\r\n * a reason.\r\n */\r\n public static encrypt(plaintext: Uint8Array,\r\n contentKey: CoseKey,\r\n recipients: readonly CoseRecipient[],\r\n options: EncryptOptions): CoseEncrypt {\r\n\r\n const algorithm = requireAesGcm(contentKey);\r\n\r\n requireUsable(contentKey, algorithm);\r\n\r\n const protectedHeader = new CoseHeaders([\r\n [label(HeaderLabel.algorithm), algorithmToCbor(algorithm)],\r\n ]);\r\n\r\n const protectedBytes = protectedHeader.toProtectedBytes();\r\n\r\n const ciphertext = aesGcmEncrypt(contentKey.privateKeyBytes(),\r\n options.iv,\r\n plaintext,\r\n encStructure(ENCRYPT_CONTEXT, protectedBytes,\r\n options.externalAad ?? null));\r\n\r\n return new CoseEncrypt(protectedBytes,\r\n new CoseHeaders([[label(HeaderLabel.iv), cbor.bytes(options.iv)]]),\r\n options.detachPayload === true ? null : ciphertext,\r\n recipients,\r\n options.tagged ?? true);\r\n\r\n }\r\n\r\n\r\n /**\r\n * Decrypt this message with a key one of its recipients was built for.\r\n *\r\n * Every recipient is tried, because a party holding one key does not\r\n * generally know which entry in the list is theirs. A recipient that does\r\n * not yield a key is not an error — it is somebody else's.\r\n */\r\n public decrypt(key: CoseKey, options: DecryptOptions = {}): Decryption {\r\n\r\n if (key.keyType !== KEY_TYPE_SYMMETRIC)\r\n return notDecrypted(`A COSE_Encrypt message needs a key of key type Symmetric, but a key of key type ${String(key.keyType)} was given!`);\r\n\r\n let tried = 0;\r\n\r\n for (const recipient of this.recipients) {\r\n\r\n const contentKey = recipient.contentKey(key);\r\n\r\n if (contentKey === null)\r\n continue;\r\n\r\n tried++;\r\n\r\n const result = this.decryptWith(contentKey, ENCRYPT_CONTEXT, options);\r\n\r\n if (result.decrypted)\r\n return result;\r\n\r\n }\r\n\r\n return notDecrypted(tried === 0\r\n ? 'None of the recipients of this COSE_Encrypt message yielded a content key for the given key!'\r\n : 'A recipient yielded a content key, but the ciphertext did not authenticate under it!');\r\n\r\n }\r\n\r\n\r\n /** Read a COSE_Encrypt message, tagged or not. */\r\n public static parse(input: Uint8Array | CborValue): CoseEncrypt {\r\n\r\n const { isTagged, items } = untag(input, COSE_ENCRYPT_TAG, 4, 'COSE_Encrypt');\r\n\r\n\r\n const [protectedBytes, unprotected, ciphertext, recipients] = items;\r\n\r\n if (recipients?.type !== 'array' || recipients.items.length === 0)\r\n throw new CoseError('A COSE_Encrypt message must carry a non-empty array of recipients!');\r\n\r\n return new CoseEncrypt(bytesOfProtected(protectedBytes, 'COSE_Encrypt'),\r\n CoseHeaders.parse(unprotected!),\r\n ciphertextOf(ciphertext!, 'COSE_Encrypt'),\r\n recipients.items.map(each => CoseRecipient.parse(each)),\r\n isTagged);\r\n\r\n }\r\n\r\n\r\n /** The CBOR form of this message. */\r\n public toCbor(): CborValue {\r\n\r\n const message = cbor.array([\r\n cbor.bytes(this.protectedHeaderBytes),\r\n this.unprotectedHeader.toCbor(),\r\n this.ciphertext !== null ? cbor.bytes(this.ciphertext) : cbor.nullValue,\r\n cbor.array(this.recipients.map(each => each.toCbor())),\r\n ]);\r\n\r\n return this.isTagged ? cbor.tag(COSE_ENCRYPT_TAG, message) : message;\r\n\r\n }\r\n\r\n\r\n /** The CBOR encoding of this message. */\r\n public toBytes(): Uint8Array {\r\n return encode(this.toCbor());\r\n }\r\n\r\n\r\n public toString(): string {\r\n return `COSE_Encrypt${this.algorithm !== null ? ` ${this.algorithm.name}` : ''}, ${String(this.recipients.length)} recipient(s)`;\r\n }\r\n\r\n}\r\n\r\n\r\n// ---------------------------------------------------------------- helpers ---\r\n\r\nfunction untag(input: Uint8Array | CborValue,\r\n tag: number,\r\n elements: number,\r\n what: string): { isTagged: boolean; items: readonly (CborValue | undefined)[] } {\r\n\r\n const value = input instanceof Uint8Array ? decode(input) : input;\r\n\r\n let isTagged = false;\r\n let message = value;\r\n\r\n if (message.type === 'tag') {\r\n\r\n if (message.tag !== BigInt(tag))\r\n throw new CoseError(`A ${what} message must be tagged with CBOR tag ${String(tag)}, but was tagged with CBOR tag ${String(message.tag)}!`);\r\n\r\n isTagged = true;\r\n message = message.value;\r\n\r\n }\r\n\r\n if (message.type !== 'array')\r\n throw new CoseError(`A ${what} message must be a CBOR array, but was a CBOR ${message.type}!`);\r\n\r\n if (message.items.length !== elements)\r\n throw new CoseError(`A ${what} message must be a CBOR array of ${String(elements)} elements, but had ${String(message.items.length)} element(s)!`);\r\n\r\n return { isTagged, items: message.items };\r\n\r\n}\r\n\r\n\r\nfunction bytesOfProtected(value: CborValue | undefined, what: string): Uint8Array {\r\n\r\n if (value?.type !== 'bytes')\r\n throw new CoseError(`The protected header bucket of a ${what} message must be a byte string!`);\r\n\r\n return value.value;\r\n\r\n}\r\n\r\n\r\nfunction ciphertextOf(value: CborValue, what: string): Uint8Array | null {\r\n\r\n if (value.type === 'null')\r\n return null;\r\n\r\n if (value.type !== 'bytes')\r\n throw new CoseError(`The ciphertext of a ${what} message must be a byte string, or null when it is detached!`);\r\n\r\n return value.value;\r\n\r\n}\r\n\r\n\r\n/** The AES-GCM algorithm a key names, refusing a key that names something else. */\r\nfunction requireAesGcm(key: CoseKey): CoseAlgorithm {\r\n\r\n if (key.algorithm === null)\r\n throw new CoseError('An encrypted COSE message needs a content encryption algorithm: either on the key or within the protected header bucket!');\r\n\r\n if (key.algorithm.family !== 'aesgcm')\r\n throw new CoseError(`The COSE algorithm '${key.algorithm.name}' is not a content encryption algorithm this implementation supports!`);\r\n\r\n return key.algorithm;\r\n\r\n}\r\n\r\n\r\n/**\r\n * The key checks of RFC 9053 Section 4.1.\r\n *\r\n * The width check is the one that earns its place: `A128GCM` and `A256GCM` are\r\n * one cipher and two identifiers, so a key of the wrong width is not a\r\n * different strength but a different algorithm, and letting it through would\r\n * silently produce a message nobody can read.\r\n */\r\nfunction requireUsable(key: CoseKey, algorithm: CoseAlgorithm): void {\r\n\r\n if (algorithm.family !== 'aesgcm')\r\n throw new CoseError(`The COSE algorithm '${algorithm.name}' is not a content encryption algorithm this implementation supports!`);\r\n\r\n if (key.keyType !== KEY_TYPE_SYMMETRIC)\r\n throw new CoseError(`An encrypted COSE message needs a key of key type Symmetric [RFC 9053, Section 4.1], but a key of key type ${String(key.keyType)} was given!`);\r\n\r\n if (key.algorithm !== null && key.algorithm.id !== algorithm.id)\r\n throw new CoseError(`This message is to be encrypted with '${algorithm.name}', but the key names '${key.algorithm.name}' [RFC 9053, Section 4.1]!`);\r\n\r\n const width = key.privateKeyBytes().length;\r\n\r\n if (algorithm.keySize !== null && width !== algorithm.keySize)\r\n throw new CoseError(`The algorithm '${algorithm.name}' needs a ${String(algorithm.keySize)}-byte key, but a ${String(width)}-byte key was given!`);\r\n\r\n}\r\n"]}