@owf/cose 0.7.0-alpha-20261102161059 → 0.7.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.
- package/dist/index.d.mts +10 -0
- package/dist/index.mjs +90 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.d.mts
CHANGED
|
@@ -509,6 +509,16 @@ export declare enum SignatureAlgorithm {
|
|
|
509
509
|
ES256 = -7,
|
|
510
510
|
ES384 = -35,
|
|
511
511
|
ES512 = -36,
|
|
512
|
+
/** RFC 9864 § 2.1: ECDSA using P-256 and SHA-256. */
|
|
513
|
+
ESP256 = -9,
|
|
514
|
+
/** RFC 9864 § 2.1: ECDSA using P-384 and SHA-384. */
|
|
515
|
+
ESP384 = -51,
|
|
516
|
+
/** RFC 9864 § 2.1: ECDSA using P-521 and SHA-512. */
|
|
517
|
+
ESP512 = -52,
|
|
518
|
+
/** RFC 9864 § 2.2: EdDSA using the Ed25519 parameter set. */
|
|
519
|
+
Ed25519 = -19,
|
|
520
|
+
/** RFC 9864 § 2.2: EdDSA using the Ed448 parameter set. */
|
|
521
|
+
Ed448 = -53,
|
|
512
522
|
PS256 = -37,
|
|
513
523
|
PS384 = -38,
|
|
514
524
|
PS512 = -39,
|
package/dist/index.mjs
CHANGED
|
@@ -731,6 +731,16 @@ let SignatureAlgorithm = /* @__PURE__ */ function(SignatureAlgorithm) {
|
|
|
731
731
|
SignatureAlgorithm[SignatureAlgorithm["ES256"] = -7] = "ES256";
|
|
732
732
|
SignatureAlgorithm[SignatureAlgorithm["ES384"] = -35] = "ES384";
|
|
733
733
|
SignatureAlgorithm[SignatureAlgorithm["ES512"] = -36] = "ES512";
|
|
734
|
+
/** RFC 9864 § 2.1: ECDSA using P-256 and SHA-256. */
|
|
735
|
+
SignatureAlgorithm[SignatureAlgorithm["ESP256"] = -9] = "ESP256";
|
|
736
|
+
/** RFC 9864 § 2.1: ECDSA using P-384 and SHA-384. */
|
|
737
|
+
SignatureAlgorithm[SignatureAlgorithm["ESP384"] = -51] = "ESP384";
|
|
738
|
+
/** RFC 9864 § 2.1: ECDSA using P-521 and SHA-512. */
|
|
739
|
+
SignatureAlgorithm[SignatureAlgorithm["ESP512"] = -52] = "ESP512";
|
|
740
|
+
/** RFC 9864 § 2.2: EdDSA using the Ed25519 parameter set. */
|
|
741
|
+
SignatureAlgorithm[SignatureAlgorithm["Ed25519"] = -19] = "Ed25519";
|
|
742
|
+
/** RFC 9864 § 2.2: EdDSA using the Ed448 parameter set. */
|
|
743
|
+
SignatureAlgorithm[SignatureAlgorithm["Ed448"] = -53] = "Ed448";
|
|
734
744
|
SignatureAlgorithm[SignatureAlgorithm["PS256"] = -37] = "PS256";
|
|
735
745
|
SignatureAlgorithm[SignatureAlgorithm["PS384"] = -38] = "PS384";
|
|
736
746
|
SignatureAlgorithm[SignatureAlgorithm["PS512"] = -39] = "PS512";
|
|
@@ -991,6 +1001,8 @@ const jwkCoseKeyMap = {
|
|
|
991
1001
|
},
|
|
992
1002
|
alg: {
|
|
993
1003
|
EdDSA: -8,
|
|
1004
|
+
Ed25519: -19,
|
|
1005
|
+
Ed448: -53,
|
|
994
1006
|
ES256: -7,
|
|
995
1007
|
ES384: -35,
|
|
996
1008
|
ES512: -36,
|
|
@@ -1021,7 +1033,16 @@ const jwkCoseKeyMap = {
|
|
|
1021
1033
|
mACVerify: 10
|
|
1022
1034
|
}
|
|
1023
1035
|
};
|
|
1024
|
-
const
|
|
1036
|
+
const swappedJwkCoseKeyMap = swapNestedMap(jwkCoseKeyMap);
|
|
1037
|
+
const coseKeyJwkMap = {
|
|
1038
|
+
...swappedJwkCoseKeyMap,
|
|
1039
|
+
alg: {
|
|
1040
|
+
...swappedJwkCoseKeyMap.alg,
|
|
1041
|
+
[-9]: "ES256",
|
|
1042
|
+
[-51]: "ES384",
|
|
1043
|
+
[-52]: "ES512"
|
|
1044
|
+
}
|
|
1045
|
+
};
|
|
1025
1046
|
const jwkCoseOptionsMap = {
|
|
1026
1047
|
kty: "keyType",
|
|
1027
1048
|
kid: "keyId",
|
|
@@ -1350,6 +1371,70 @@ const sign1DecodedSchema = z.object({
|
|
|
1350
1371
|
payload: sign1EncodedSchema.def.items[2],
|
|
1351
1372
|
signature: sign1EncodedSchema.def.items[3]
|
|
1352
1373
|
});
|
|
1374
|
+
const ecdsaCurves = [
|
|
1375
|
+
1,
|
|
1376
|
+
2,
|
|
1377
|
+
3
|
|
1378
|
+
];
|
|
1379
|
+
/**
|
|
1380
|
+
* The key type and curves each signature algorithm accepts: RFC 9053 § 2.1 and § 2.2 for the
|
|
1381
|
+
* polymorphic ECDSA and EdDSA algorithms, and RFC 9864 § 2.1 and § 2.2 for the fully-specified
|
|
1382
|
+
* ones, which fix the curve. RSA keys have no `KeyType`, so the RSA algorithms are not listed.
|
|
1383
|
+
*/
|
|
1384
|
+
const signatureAlgorithmKeys = /* @__PURE__ */ new Map([
|
|
1385
|
+
[-7, {
|
|
1386
|
+
keyType: 2,
|
|
1387
|
+
curves: ecdsaCurves
|
|
1388
|
+
}],
|
|
1389
|
+
[-35, {
|
|
1390
|
+
keyType: 2,
|
|
1391
|
+
curves: ecdsaCurves
|
|
1392
|
+
}],
|
|
1393
|
+
[-36, {
|
|
1394
|
+
keyType: 2,
|
|
1395
|
+
curves: ecdsaCurves
|
|
1396
|
+
}],
|
|
1397
|
+
[-9, {
|
|
1398
|
+
keyType: 2,
|
|
1399
|
+
curves: [1]
|
|
1400
|
+
}],
|
|
1401
|
+
[-51, {
|
|
1402
|
+
keyType: 2,
|
|
1403
|
+
curves: [2]
|
|
1404
|
+
}],
|
|
1405
|
+
[-52, {
|
|
1406
|
+
keyType: 2,
|
|
1407
|
+
curves: [3]
|
|
1408
|
+
}],
|
|
1409
|
+
[-8, {
|
|
1410
|
+
keyType: 1,
|
|
1411
|
+
curves: [6, 7]
|
|
1412
|
+
}],
|
|
1413
|
+
[-19, {
|
|
1414
|
+
keyType: 1,
|
|
1415
|
+
curves: [6]
|
|
1416
|
+
}],
|
|
1417
|
+
[-53, {
|
|
1418
|
+
keyType: 1,
|
|
1419
|
+
curves: [7]
|
|
1420
|
+
}]
|
|
1421
|
+
]);
|
|
1422
|
+
const keyTypeNames = {
|
|
1423
|
+
[2]: "EC2",
|
|
1424
|
+
[1]: "OKP"
|
|
1425
|
+
};
|
|
1426
|
+
/**
|
|
1427
|
+
* Rejects a key the algorithm is not defined for, rather than leaving it to the context, which may
|
|
1428
|
+
* pick the curve from the key alone. Only the key type and curve are compared: a key is valid for
|
|
1429
|
+
* every algorithm that accepts them, whatever its own `alg`.
|
|
1430
|
+
*/
|
|
1431
|
+
const assertKeyMatchesAlgorithm = (key, algorithm) => {
|
|
1432
|
+
if (algorithm === void 0) return;
|
|
1433
|
+
const requirement = signatureAlgorithmKeys.get(algorithm);
|
|
1434
|
+
if (!requirement) return;
|
|
1435
|
+
const { keyType, curves } = requirement;
|
|
1436
|
+
if (key.keyType !== keyType || key.curve === void 0 || !curves.includes(key.curve)) throw new CoseInvalidAlgorithmError(`Algorithm ${SignatureAlgorithm[algorithm]} requires an ${keyTypeNames[keyType]} key on curve ${curves.map((curve) => Curve[curve]).join(" or ")}`);
|
|
1437
|
+
};
|
|
1353
1438
|
var Sign1 = class Sign1 extends CborStructure {
|
|
1354
1439
|
constructor(..._args) {
|
|
1355
1440
|
super(..._args);
|
|
@@ -1455,6 +1540,8 @@ var Sign1 = class Sign1 extends CborStructure {
|
|
|
1455
1540
|
}
|
|
1456
1541
|
async verifySignature({ key, detachedPayload, externalAad }, ctx) {
|
|
1457
1542
|
if (this.payload && detachedPayload) throw new Error("Cannot provide detachedPayload when the Sign1 already contains an embedded payload");
|
|
1543
|
+
const algorithm = this.algorithm;
|
|
1544
|
+
assertKeyMatchesAlgorithm(key, algorithm);
|
|
1458
1545
|
return await ctx.verify({
|
|
1459
1546
|
toBeVerified: this.toBeSigned({
|
|
1460
1547
|
detachedPayload,
|
|
@@ -1462,7 +1549,7 @@ var Sign1 = class Sign1 extends CborStructure {
|
|
|
1462
1549
|
}),
|
|
1463
1550
|
signature: this.signature,
|
|
1464
1551
|
key,
|
|
1465
|
-
algorithm
|
|
1552
|
+
algorithm
|
|
1466
1553
|
});
|
|
1467
1554
|
}
|
|
1468
1555
|
static create(options) {
|
|
@@ -1484,6 +1571,7 @@ var Sign1 = class Sign1 extends CborStructure {
|
|
|
1484
1571
|
const signatureAlgorithm = options.algorithm ?? options.signingKey.algorithm;
|
|
1485
1572
|
if (!signatureAlgorithm) throw new CoseInvalidAlgorithmError("Could not establish signature algorithm. Either provide it in the options directly, or provide it in the signingKey");
|
|
1486
1573
|
if (!Object.values(SignatureAlgorithm).includes(signatureAlgorithm)) throw new CoseInvalidAlgorithmError("algorithm provided in the options or key is not a valid signing algorithm");
|
|
1574
|
+
assertKeyMatchesAlgorithm(options.signingKey, signatureAlgorithm);
|
|
1487
1575
|
this.structure.signature = await ctx.sign({
|
|
1488
1576
|
toBeSigned: Sign1.toBeSigned({
|
|
1489
1577
|
payload,
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["z","z","z","z"],"sources":["../src/utils/zod-error.ts","../src/utils/zod.ts","../src/cbor/cbor-x.ts","../src/cbor/error.ts","../src/cbor/parser.ts","../src/cbor/data-item.ts","../src/cbor/cbor-structure.ts","../src/cbor/describe.ts","../src/cbor/models/date.ts","../src/cbor/models/date-only.ts","../src/utils/typed-map.ts","../src/cose/error.ts","../src/cose/claims/default.ts","../src/cose/claims/cwt-payload.ts","../src/cose/headers/defaults.ts","../src/cose/headers/header-claims.ts","../src/cose/headers/protected-headers.ts","../src/cose/headers/unprotected-headers.ts","../src/cose/headers/x5chain.ts","../src/cose/key/curve.ts","../src/cose/key/key-operation.ts","../src/cose/key/key-type.ts","../src/cose/key/jwk.ts","../src/cose/key/key.ts","../src/cose/mac0.ts","../src/cose/sign1.ts","../src/cose/cwt.ts"],"sourcesContent":["import z from 'zod'\nimport { createErrorMap, fromError } from 'zod-validation-error'\n\nz.config({\n customError: createErrorMap(),\n})\n\nfunction formatZodError(error?: z.ZodError): string {\n if (!error) return ''\n\n return fromError(error, {\n prefix: '',\n prefixSeparator: '✖ ',\n issueSeparator: '\\n✖ ',\n unionSeparator: '\\n OR ✖ ',\n }).toString()\n}\n\nimport type { ZodError } from 'zod'\n\nexport class ValidationError extends Error {\n public zodError: ZodError | undefined\n\n constructor(message: string, zodError?: ZodError) {\n super(message)\n\n const formattedError = zodError ? formatZodError(zodError) : ''\n this.message = `${message}\\n${formattedError}`\n\n Object.defineProperty(this, 'zodError', {\n value: zodError,\n writable: false,\n enumerable: false,\n })\n }\n}\n","import z from 'zod'\nimport type { $ZodType } from 'zod/v4/core'\nimport { ValidationError } from './zod-error'\n\nexport const zUint8Array = z.instanceof<typeof Uint8Array<ArrayBufferLike>>(Uint8Array)\n\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\ntype ZodTypeAny = $ZodType<any, any, any>\n\nexport function parseStructureWithErrorHandling<Schema extends ZodTypeAny>(\n structureName: string,\n schema: Schema,\n data: unknown,\n customErrorMessage?: string\n): z.infer<Schema> {\n const parseResult = z.safeParse(schema, data)\n\n if (!parseResult.success) {\n throw new ValidationError(customErrorMessage ?? `Error decoding ${structureName}`, parseResult.error)\n }\n\n return parseResult.data\n}\n\nexport function decodeStructureWithErrorHandling<Schema extends ZodTypeAny>(\n structureName: string,\n schema: Schema,\n data: z.input<Schema>,\n customErrorMessage?: string\n): z.infer<Schema> {\n const decodeResult = z.safeDecode(schema, data)\n\n if (!decodeResult.success) {\n throw new ValidationError(customErrorMessage ?? `Error decoding ${structureName}`, decodeResult.error)\n }\n\n return decodeResult.data\n}\n\nexport function encodeStructureWithErrorHandling<Schema extends ZodTypeAny>(\n structureName: string,\n schema: Schema,\n data: z.output<Schema>,\n customErrorMessage?: string\n): z.input<Schema> {\n const encodeResult = z.safeEncode(schema, data)\n\n if (!encodeResult.success) {\n throw new ValidationError(customErrorMessage ?? `Error encoding ${structureName}`, encodeResult.error)\n }\n\n return encodeResult.data\n}\n","import type { Tag as CborXTag } from 'cbor-x'\nimport * as cborXDecode from 'cbor-x/decode'\n\nexport type { Options } from 'cbor-x'\nexport { addExtension, Encoder } from 'cbor-x/encode'\n\nexport const Tag = (cborXDecode as unknown as { Tag: typeof CborXTag }).Tag\nexport type Tag = CborXTag\n","// biome-ignore format: no explanation\nclass CborError extends Error {\n // NOTE: declared explicitly rather than passing `{ cause }` to `super`, as the\n // project targets ES2020 and `Error.cause` was only added in ES2022.\n public readonly cause?: unknown\n\n constructor(message: string = new.target.name, options?: { cause?: unknown }) {\n super(message)\n this.name = new.target.name\n this.cause = options?.cause\n }\n}\n\nexport class CborDecodeError extends CborError {}\nexport class CborEncodeError extends CborError {}\n","import { Encoder, type Options } from './cbor-x'\nimport { DataItem } from './data-item'\nimport { CborDecodeError, CborEncodeError } from './error'\n\nexport type CborOptions = Options & {\n unwrapTopLevelDataItem?: boolean\n}\n\nconst encoderDefaults: CborOptions = {\n tagUint8Array: false,\n useRecords: false,\n mapsAsObjects: false,\n unwrapTopLevelDataItem: true,\n variableMapSize: true,\n}\n\nexport const cborDecode = <T>(input: Uint8Array, options: CborOptions = encoderDefaults): T => {\n const params = { ...encoderDefaults, ...options }\n const enc = new Encoder(params)\n\n let decoded: unknown\n try {\n decoded = enc.decode(input)\n } catch (error) {\n // cbor-x errors ('Data read, but end of buffer not reached', 'Unexpected end of CBOR data',\n // ...) give no indication of what was being decoded. Wrap them so callers can tell a\n // malformed input apart from a structurally valid one that failed validation later on.\n throw new CborDecodeError(\n `Unable to decode ${input.length} bytes as CBOR: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n )\n }\n\n return params.unwrapTopLevelDataItem && typeof decoded === 'object' && decoded instanceof DataItem\n ? (decoded.data as T)\n : (decoded as T)\n}\n\nexport const cborEncode = (obj: unknown, options: Options = encoderDefaults): Uint8Array => {\n const params = { ...encoderDefaults, ...options }\n const enc = new Encoder(params)\n\n try {\n return Uint8Array.from(enc.encode(obj))\n } catch (error) {\n throw new CborEncodeError(\n `Unable to encode value as CBOR: ${error instanceof Error ? error.message : String(error)}`,\n {\n cause: error,\n }\n )\n }\n}\n","import z from 'zod'\nimport { addExtension } from './cbor-x'\nimport { cborDecode, cborEncode } from './parser'\n\nexport const zDataItemCodec = (outputSchema: z.ZodType) =>\n z.codec(z.instanceof(DataItem), outputSchema, {\n encode: (data) => DataItem.fromData(data),\n decode: (dataItem) => dataItem.data,\n })\n\nexport type DataItemOptions<T = unknown> =\n | {\n data: T\n buffer: Uint8Array\n }\n | { data: T }\n | { buffer: Uint8Array }\n\n/**\n * DataItem is an extension defined https://www.rfc-editor.org/rfc/rfc8949.html#name-encoded-cbor-data-item\n * > Sometimes it is beneficial to carry an embedded CBOR data item that is\n * > not meant to be decoded immediately at the time the enclosing data item is being decoded.\n *\n * The idea of this class is to provide lazy encode and decode of cbor data.\n *\n * Due to a bug in the cbor-x library, we are eagerly encoding the data in the constructor.\n * https://github.com/kriszyp/cbor-x/issues/83\n *\n */\nexport class DataItem<T = unknown> {\n #data?: T\n #buffer: Uint8Array\n\n public constructor(options: DataItemOptions<T>) {\n if (!('data' in options) && !('buffer' in options)) {\n throw new Error('DataItem must be initialized with either the data or a buffer')\n }\n\n if ('data' in options) this.#data = options.data\n this.#buffer = 'buffer' in options ? options.buffer : cborEncode(options.data)\n }\n\n public get data(): T {\n if (!this.#data) {\n this.#data = cborDecode(this.#buffer) as T\n }\n return this.#data\n }\n\n public get buffer(): Uint8Array {\n return this.#buffer\n }\n\n public static fromData<T>(data: T): DataItem<T> {\n return new DataItem({ data })\n }\n\n public static fromBuffer<T>(buffer: Uint8Array): DataItem<T> {\n return new DataItem({ buffer })\n }\n}\n\naddExtension({\n Class: DataItem,\n tag: 24,\n encode: (instance: DataItem<unknown>, encode) => {\n return encode(instance.buffer)\n },\n decode: (buffer: Uint8Array): object => {\n return DataItem.fromBuffer(buffer)\n },\n})\n","// biome-ignore-all lint: @biomejs/biome seems to change the `new this(...)` calls into `new CborStructure(...)` which seems to cause a bug for this specific use case. We cannot alias to `thiz` or disable a specific rule\n\nimport { z } from 'zod'\nimport {\n decodeStructureWithErrorHandling,\n encodeStructureWithErrorHandling,\n parseStructureWithErrorHandling,\n} from '../utils/zod'\nimport { Tag } from './cbor-x'\nimport { DataItem } from './data-item'\nimport { cborDecode, cborEncode } from './parser'\n\nexport type CborEncodeOptions = {\n asDataItem?: boolean\n}\n\nexport type AnyCborStructure = CborStructure<any, any>\nexport type EncodedStructureType<T> = T extends CborStructure<infer EncodedStructure, unknown> ? EncodedStructure : any\nexport type DecodedStructureType<T> = T extends CborStructure<unknown, infer DecodedStructure> ? DecodedStructure : any\n\nexport type CborStructureStaticThis<T extends AnyCborStructure> = {\n new (structure: any): T\n encodingSchema: z.ZodType<any, any, any> | undefined\n fromEncodedStructure: (encodedStructure: EncodedStructureType<T>) => { decodedStructure: DecodedStructureType<T> }\n}\n\nexport class CborStructure<EncodedStructure = unknown, DecodedStructure = EncodedStructure> {\n protected structure: DecodedStructure\n protected _tag: number | undefined\n\n public constructor(structure: DecodedStructure) {\n this.structure = structure\n }\n\n public get decodedStructure(): DecodedStructure {\n return this.structure\n }\n\n /**\n * Static getter for the Zod codec schema that defines the CBOR structure.\n * Subclasses CAN override this to provide their specific schema for automatic encoding/decoding.\n * The schema should be a Zod schema or codec that handles validation and transformation.\n * If not provided, subclasses must override encode(), decode(), and fromEncodedStructure().\n */\n public static get encodingSchema(): z.ZodType | undefined {\n return undefined\n }\n\n /**\n * Returns the encoded structure that will be serialized to CBOR.\n * By default, returns the protected structure property.\n * Override if custom encoding logic is needed.\n */\n public get encodedStructure(): EncodedStructure {\n const encodingSchema = (this.constructor as typeof CborStructure).encodingSchema\n if (!encodingSchema) {\n throw new Error('encodedStructure must be implemented when encodingSchema is not provided')\n }\n\n return encodeStructureWithErrorHandling(this.constructor.name, encodingSchema, this.structure) as EncodedStructure\n }\n\n /**\n * Encodes this structure to CBOR bytes.\n */\n public encode(options?: CborEncodeOptions): Uint8Array {\n const encodedStructure = options?.asDataItem ? DataItem.fromData(this.encodedStructure) : this.encodedStructure\n const tagged = this._tag ? new Tag(encodedStructure, this._tag) : encodedStructure\n\n return cborEncode(tagged)\n }\n\n /**\n * Decodes CBOR bytes into a structure instance.\n * Uses the encodingSchema's decode() method to validate and transform the decoded data.\n */\n public static decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n const rawStructure = cborDecode(bytes)\n\n // May feel weird, but using new this makes TypeScript understand we may return a subclass\n return new this(this.fromEncodedStructure(rawStructure as EncodedStructureType<T>).decodedStructure)\n }\n\n /**\n * Creates a structure instance from the encoded CBOR structure (after calling cborDecode).\n *\n * Uses the encodingSchema's decode() method to validate and transform the structure if available.\n * Otherwise, subclasses must override this method.\n */\n public static fromEncodedStructure<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n encodedStructure: EncodedStructureType<T>\n ): T {\n if (!this.encodingSchema) {\n throw new Error('fromEncodedStructure must be implemented when encodingSchema is not provided')\n }\n\n return new this(decodeStructureWithErrorHandling(this.name, this.encodingSchema, encodedStructure))\n }\n\n public static fromDataItem<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, dataItem: unknown): T {\n return new this(\n parseStructureWithErrorHandling(\n this.name,\n z\n .instanceof(DataItem)\n .transform((di) => di.data)\n .transform((d) => this.fromEncodedStructure(d as any).decodedStructure),\n dataItem,\n `Error decoding ${this.name} from DateItem`\n )\n )\n }\n\n /**\n * Creates a structure instance from the decoded structure.\n *\n * Uses the encodingSchema's parse method to validate the structure if available.\n * Otherwise, subclasses must override this method.\n */\n public static fromDecodedStructure<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n decodedStructure: DecodedStructureType<T>\n ): T {\n const encodingSchema = this.encodingSchema\n if (!encodingSchema) {\n throw new Error('fromDecodedStructure must be implemented when encodingSchema is not provided')\n }\n\n // When the schema is a codec, we need to validate it against the output schema, not the input schema\n const decodedSchema = encodingSchema instanceof z.ZodPipe ? encodingSchema.out : encodingSchema\n\n return new this(parseStructureWithErrorHandling(this.name, decodedSchema, decodedStructure))\n }\n}\n","import { Tag } from './cbor-x'\nimport { DataItem } from './data-item'\n\nconst MAX_DESCRIBED_STRING_LENGTH = 40\n\n/**\n * Describes a decoded CBOR value in a form suitable for error messages, so a caller can tell\n * what their input actually was instead of only learning what it wasn't.\n *\n * Only describes the shape of the top-level value; it does not recurse into containers.\n */\nexport function describeCborValue(value: unknown): string {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n\n if (value instanceof Tag) return `a CBOR value tagged with tag ${value.tag}`\n if (value instanceof DataItem) return 'an encoded CBOR data item (tag 24)'\n\n if (Array.isArray(value)) {\n return `an untagged array with ${value.length} ${value.length === 1 ? 'element' : 'elements'}`\n }\n if (value instanceof Map) return `an untagged map with ${value.size} ${value.size === 1 ? 'entry' : 'entries'}`\n if (value instanceof Uint8Array) return `a byte string of ${value.length} bytes`\n\n if (typeof value === 'string') {\n const truncated =\n value.length > MAX_DESCRIBED_STRING_LENGTH ? `${value.slice(0, MAX_DESCRIBED_STRING_LENGTH)}…` : value\n return `the text string '${truncated}'`\n }\n\n if (typeof value === 'object') return `a value of type ${value.constructor?.name ?? 'object'}`\n\n return `the ${typeof value} value '${String(value)}'`\n}\n","import { addExtension } from '../cbor-x'\n\n// tdate data item shall contain a date-time string as specified in RFC 3339 (with no fraction of seconds)\n// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6\naddExtension({\n Class: Date,\n tag: 0,\n encode: (date: Date, encode) => encode(`${date.toISOString().split('.')[0]}Z`),\n decode: (isoStringDateTime: string) => new Date(isoStringDateTime),\n})\n","import { addExtension } from '../cbor-x'\n\nconst customInspectSymbol = Symbol.for('nodejs.util.inspect.custom')\nexport class DateOnly {\n private date: Date\n\n public constructor(date?: string) {\n this.date = date ? new Date(date) : new Date()\n }\n\n get [Symbol.toStringTag]() {\n return DateOnly.name\n }\n\n toString() {\n return this.toISOString()\n }\n\n toJSON() {\n return this.toISOString()\n }\n\n toISOString(): string {\n return this.date.toISOString().split('T')[0]\n }\n\n [customInspectSymbol](): string {\n return this.toISOString()\n }\n}\n\n// full-date data item shall contain a full-date string as specified in RFC 3339\n// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6\naddExtension({\n Class: DateOnly,\n tag: 1004,\n encode: (date: DateOnly, encode) => encode(date.toISOString()),\n decode: (isoStringDate: string) => new DateOnly(isoStringDate),\n})\n","import { z } from 'zod'\nimport type zCore from 'zod/v4/core'\n\n/**\n * TypedMap provides compile-time type safety for Maps where each key has its own specific value type.\n * Unlike Map<K, V> which has the same value type V for all keys, TypedMap<Schema, OptionalKeys>\n * allows different value types per key (heterogeneous values).\n *\n * Example:\n * type CoseKeySchema = {\n * [CoseKeyParameter.KeyType]: KeyType // number key → KeyType value\n * [CoseKeyParameter.Curve]: Curve // number key → Curve value\n * [CoseKeyParameter.X]: Uint8Array // number key → Uint8Array value\n * }\n *\n * const map = new TypedMap<CoseKeySchema>()\n * map.get(CoseKeyParameter.KeyType) // TypeScript knows this is KeyType!\n * map.get(CoseKeyParameter.Curve) // TypeScript knows this is Curve!\n * map.get(CoseKeyParameter.X) // TypeScript knows this is Uint8Array!\n *\n * @template Schema - Object type mapping keys to their value types\n * @template OptionalKeys - Union of keys that are optional (can be absent)\n */\n\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\nexport class TypedMap<Schema extends Record<PropertyKey, any>, OptionalKeys extends keyof Schema = never> {\n private readonly map: Map<keyof Schema, Schema[keyof Schema]>\n\n /**\n * Called whenever an entry is added, changed or removed. Set by a structure that caches the bytes\n * it was decoded from, so that the cache is dropped as soon as the map no longer matches them.\n *\n * NOTE: only changes made through this map are seen. Mutating a value in place —\n * `map.get(key)[0] = 1` — does not go through `set`/`delete`/`clear` and does not fire this, so a\n * structure that caches its encoded form has to be told about such a change explicitly.\n */\n public onChange?: () => void\n\n constructor(entries?: (readonly [keyof Schema, Schema[keyof Schema]])[] | null) {\n this.map = new Map(entries)\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n public static fromMap<Schema extends Record<PropertyKey, any>, OptionalKeys extends keyof Schema = never>(\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n map: Map<any, any>\n ) {\n return new TypedMap<Schema, OptionalKeys>(Array.from(map.entries()))\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n public static fromObject<Schema extends Record<PropertyKey, any>, OptionalKeys extends keyof Schema = never>(\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n object: Record<string | number, any>\n ) {\n return new TypedMap<Schema, OptionalKeys>(Array.from(Object.entries(object)))\n }\n\n /**\n * Type-safe get that returns the correct value type for each key.\n * Required keys return T, optional keys return T | undefined.\n */\n get<K extends keyof Schema>(key: K): K extends OptionalKeys ? Schema[K] | undefined : Schema[K] {\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n return this.map.get(key) as any\n }\n\n /**\n * Type-safe set that ensures the value matches the key's type\n */\n set<K extends keyof Schema>(key: K, value: Schema[K]): this {\n this.map.set(key, value)\n this.onChange?.()\n return this\n }\n\n has(key: keyof Schema): boolean {\n return this.map.has(key)\n }\n\n delete(key: keyof Schema): boolean {\n const deleted = this.map.delete(key)\n if (deleted) this.onChange?.()\n return deleted\n }\n\n clear(): void {\n if (this.map.size === 0) return\n this.map.clear()\n this.onChange?.()\n }\n\n get size(): number {\n return this.map.size\n }\n\n keys(): IterableIterator<keyof Schema> {\n return this.map.keys()\n }\n\n values(): IterableIterator<Schema[keyof Schema]> {\n return this.map.values()\n }\n\n entries(): IterableIterator<[keyof Schema, Schema[keyof Schema]]> {\n return this.map.entries()\n }\n\n forEach(\n callbackfn: (value: Schema[keyof Schema], key: keyof Schema, map: Map<keyof Schema, Schema[keyof Schema]>) => void,\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n thisArg?: any\n ): void {\n this.map.forEach(callbackfn, thisArg)\n }\n\n [Symbol.iterator](): IterableIterator<[keyof Schema, Schema[keyof Schema]]> {\n return this.map[Symbol.iterator]()\n }\n\n toMap(): Map<keyof Schema, Schema[keyof Schema]> {\n return new Map(this.map)\n }\n}\n\n// Helper type to build schema from entries array\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\ntype EntriesArrayToSchema<T extends ReadonlyArray<readonly [any, any]>> = {\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n [K in T[number][0]]: Extract<T[number], readonly [K, any]>[1]\n}\n\n/**\n * This checks whether the property is exact optional. exact optional means that the value cannot be undefined, but if used\n * in an object the key can be omitted. This is important for CBOR structures, as undefined will be encoded, and thus must be\n * omitted in most cases.\n *\n * Zod recommend to check for optionality by just parsing undefined.\n */\nconst isExactOptional = (schema: z.ZodType) =>\n !schema.safeParse(undefined).success && z.object({ test: schema }).safeParse({}).success\n\n/**\n * Names a map key for an error message: `ExpirationTime (4)` when `keyLabels` has a name for the\n * key, and the bare label otherwise.\n *\n * `RegisteredCwtClaimKey[4]` is `'ExpirationTime'` for a numeric enum, so a reverse-mapped string\n * is a name. A numeric value is the enum's forward mapping and not a name.\n *\n * @see the `keyLabels` option of {@link typedMap}\n */\nexport function keyLabel(key: string | number, keyLabels?: Record<string | number, unknown>): string {\n const label = keyLabels?.[key]\n return typeof label === 'string' ? `${label} (${key})` : `${key}`\n}\n\nexport type EntriesBase = ReadonlyArray<\n readonly [\n string | number, // for now we only allow string or number keys\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n z.ZodType<any>,\n ]\n>\n\n/**\n * A `TypedMap` with any schema. Useful as a generic constraint for structures that are generic over\n * the shape of their map, where the concrete schema is supplied by a subclass.\n */\n// biome-ignore lint/suspicious/noExplicitAny: intentionally unconstrained, used as a generic bound\nexport type AnyTypedMap = TypedMap<any, any>\n\ntype EntryKey<Entry> = Entry extends readonly [infer Key, z.ZodType] ? Key : never\n\n/**\n * Drops every entry from `Entries` whose key is present in `Keys`, preserving tuple order.\n */\ntype WithoutEntryKeys<Entries extends EntriesBase, Keys> = Entries extends readonly [\n infer Head,\n ...infer Rest extends EntriesBase,\n]\n ? EntryKey<Head> extends Keys\n ? WithoutEntryKeys<Rest, Keys>\n : readonly [Head, ...WithoutEntryKeys<Rest, Keys>]\n : readonly []\n\nexport type ExtendedEntries<Base extends EntriesBase, Extra extends EntriesBase> = readonly [\n ...WithoutEntryKeys<Base, Extra[number][0]>,\n ...Extra,\n]\n\n/**\n * Merges a base set of `typedMap` entries with additional ones, so a structure can be extended for a\n * specific profile (e.g. a status list CWT payload extending the registered CWT claims).\n *\n * An entry in `extra` that reuses a key from `base` replaces it, both in the resulting type and at\n * runtime. That is what makes it possible to narrow an inherited claim, e.g. turning the optional\n * registered `sub` claim into a required one. Without the replacement the two schemas for the same\n * key would collapse into a union and the key would stay optional.\n */\nexport function extendTypedMapEntries<const Base extends EntriesBase, const Extra extends EntriesBase>(\n base: Base,\n extra: Extra\n): ExtendedEntries<Base, Extra> {\n const overriddenKeys = new Set<string | number>(extra.map(([key]) => key))\n\n return [...base.filter(([key]) => !overriddenKeys.has(key)), ...extra] as unknown as ExtendedEntries<Base, Extra>\n}\n\ntype InferredEntries<Entries extends EntriesBase> = {\n [K in keyof Entries]: readonly [Entries[K][0], z.infer<Entries[K][1]>]\n}\ntype InferredSchema<Entries extends EntriesBase> = EntriesArrayToSchema<InferredEntries<Entries>>\n\ntype OptionalKeys<Entries extends EntriesBase> = Entries[number] extends infer E\n ? E extends readonly [infer K, infer V]\n ? // biome-ignore lint/suspicious/noExplicitAny: no explanation\n V extends z.ZodExactOptional<any>\n ? K\n : never\n : never\n : never\n\n/**\n * Utility function to create a typed map codec.\n * Takes an array of [key, valueSchema] entries to support any key type (including non-string keys for CBOR).\n *\n * Example:\n * const coseKeyMap = typedMap([\n * [CoseKeyParameter.KeyType, z.number()],\n * [CoseKeyParameter.Curve, z.number()],\n * [CoseKeyParameter.X, z.instanceof(Uint8Array)]\n * ] as const)\n *\n * The resulting schema validates a Map and transforms it to TypedMap<Schema, never>.\n */\nexport function typedMap<const Entries extends EntriesBase>(\n entries: Entries,\n {\n allowAdditionalKeys = true,\n keyLabels,\n encode,\n decode,\n }: {\n /**\n * Whether to allow additional keys in the typed map\n *\n * @default true\n */\n allowAdditionalKeys?: boolean\n\n /**\n * Human-readable names for the map's keys, used in validation errors so that a bare CBOR\n * label (`Expected key '4' to be defined.`) is not all a reader gets.\n *\n * A numeric TypeScript enum can be passed straight in — its reverse mapping supplies the\n * names — and several can be merged with a spread:\n *\n * typedMap(entries, { keyLabels: { ...RegisteredCwtClaimKey, ...StatusListCwtClaimKey } })\n *\n * An explicit record (`{ 4: 'exp' }`) works too. Keys with no name keep their raw label.\n */\n keyLabels?: Record<string | number, unknown>\n\n /**\n * Allows overriding the encode function. The original encode method is passed as second\n * argument, so you can use this method to pre/post process\n */\n encode?: (\n decoded: TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>,\n originalEncode: (decoded: TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>) => Map<unknown, unknown>\n ) => Map<unknown, unknown>\n\n /**\n * Allows overriding the decode function. The original decode method is passed as second\n * argument, so you can use this method to pre/post process\n */\n decode?: (\n encoded: Map<unknown, unknown>,\n originalDecode: (decoded: Map<unknown, unknown>) => TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>\n ) => TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>\n } = {}\n) {\n // Create a set of required keys (non-optional) for validation\n const requiredKeys = entries.filter(([, valueSchema]) => !isExactOptional(valueSchema)).map(([key]) => key)\n\n const schemaMap = new Map(entries)\n\n const labelFor = (key: string | number) => keyLabel(key, keyLabels)\n\n const originalEncode = (decoded: TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>) => decoded.toMap()\n const originalDecode = (encoded: Map<unknown, unknown>) =>\n TypedMap.fromMap<InferredSchema<Entries>, OptionalKeys<Entries>>(encoded)\n\n return z.codec(\n // Input is untyped map\n z.map(z.unknown(), z.unknown()),\n // Output is typed map\n z.instanceof<typeof TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>>(TypedMap).superRefine((map, ctx) => {\n // Check there's no additional keys in the map if not allowed\n const additionalKeys = Array.from(map.keys()).filter((key) => !schemaMap.has(key as string | number))\n if (additionalKeys.length > 0 && !allowAdditionalKeys) {\n for (const additionalKey of additionalKeys) {\n if (typeof additionalKey !== 'string' && typeof additionalKey !== 'number') {\n ctx.addIssue({\n code: 'invalid_key',\n origin: 'map',\n continue: true,\n path: [],\n input: map,\n issues: [],\n message: 'Key found in map that is not a string or number',\n })\n } else {\n ctx.addIssue({\n code: 'invalid_key',\n origin: 'map',\n continue: true,\n path: [additionalKey],\n input: map,\n issues: [],\n message: `Unexpected key '${labelFor(additionalKey)}' found in map, additional keys are not allowed.`,\n })\n }\n }\n }\n\n for (const [key, valueSchema] of schemaMap.entries()) {\n const hasKey = map.has(key)\n const value = map.get(key)\n\n if (!hasKey && requiredKeys.includes(key)) {\n ctx.addIssue({\n code: 'invalid_value',\n continue: true,\n message: `Expected key '${labelFor(key)}' to be defined.`,\n // NOTE: stringified for the same reason as the value issues below\n path: [`${key}`],\n values: [],\n input: value,\n })\n continue\n }\n\n // If key is not in the map, and also not required, skip validation\n if (!hasKey && !requiredKeys.includes(key)) {\n continue\n }\n\n const parseResult = valueSchema.safeParse(value)\n if (!parseResult.success) {\n for (const issue of parseResult.error.issues) {\n ctx.addIssue({\n ...issue,\n // NOTE: if we use numbers, zod-validation-error will use \"index\", thinking\n // it's an array, that's confusing. The value schema owns the message, so the\n // key's name has to travel on the path.\n path: [labelFor(key), ...issue.path],\n } as zCore.$ZodSuperRefineIssue)\n }\n }\n }\n }),\n {\n decode: (input) => (decode ? decode(input, originalDecode) : originalDecode(input)),\n encode: (output) => (encode ? encode(output, originalEncode) : originalEncode(output)),\n }\n )\n}\n","// biome-ignore format: no explanation\nclass CoseError extends Error {\n // NOTE: declared explicitly rather than passing `{ cause }` to `super`, as the\n // project targets ES2020 and `Error.cause` was only added in ES2022.\n public readonly cause?: unknown\n\n constructor(message: string = new.target.name, options?: { cause?: unknown }) {\n super(message)\n this.name = new.target.name\n this.cause = options?.cause\n }\n}\n\nexport class CoseUnsupportedMacError extends CoseError {}\nexport class CoseInvalidSignatureError extends CoseError {}\nexport class CoseInvalidAlgorithmError extends CoseError {}\nexport class CosePayloadMustBeNullError extends CoseError {}\nexport class CosePayloadMustBeDefinedError extends CoseError {}\nexport class CosePayloadInvalidStructureError extends CoseError {}\nexport class CoseInvalidTypeForKeyError extends CoseError {}\nexport class CoseInvalidValueForKtyError extends CoseError {}\nexport class CoseInvalidKtyForRawError extends CoseError {}\nexport class CoseXNotDefinedError extends CoseError {}\nexport class CoseYNotDefinedError extends CoseError {}\nexport class CoseDNotDefinedError extends CoseError {}\nexport class CoseKNotDefinedError extends CoseError {}\nexport class CoseEphemeralMacKeyIsRequiredError extends CoseError {}\nexport class CoseCertificateNotFoundError extends CoseError {}\n\n/**\n * RFC 9360: the end-entity certificate \"MUST be integrity protected by COSE\". An `x5chain` in the\n * unprotected header is therefore only accepted when a protected `x5t` matches its leaf.\n */\nexport class CoseX5ChainNotBoundError extends CoseError {}\nexport class CoseKeyTypeNotSupportedForPrivateKeyExtractionError extends CoseError {}\n\n/** The CWT carries a detached payload (`null`), which cannot be decoded into a claims set. */\nexport class CwtDetachedPayloadError extends CoseError {}\n\n/** The CWT payload is not a valid claims set for the CWT type it was decoded as. */\nexport class CwtPayloadDecodeError extends CoseError {}\n\n/** The CWT carries neither a signature nor an authentication tag, so there is nothing to verify. */\nexport class CwtNotSignedError extends CoseError {}\n\n/** No verification context was provided for the COSE structure the CWT is carried in. */\nexport class CwtMissingVerifyContextError extends CoseError {}\n\n/**\n * A claim required by the profile the token is verified against is missing, a claim does not match\n * the value it was expected to have, or the token is outside its validity window.\n */\nexport class CwtClaimVerificationError extends CoseError {}\n","/**\n *\n * Registered CWT claim keys\n * @see https://www.rfc-editor.org/rfc/rfc8392#section-3.1\n *\n */\nexport enum RegisteredCwtClaimKey {\n Issuer = 1,\n Subject = 2,\n Audience = 3,\n ExpirationTime = 4,\n NotBefore = 5,\n IssuedAt = 6,\n CwtId = 7,\n}\n","import { dateToSeconds, secondsToDate } from '@owf/identity-common'\nimport z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport {\n type AnyTypedMap,\n type EntriesBase,\n type ExtendedEntries,\n extendTypedMapEntries,\n keyLabel,\n TypedMap,\n typedMap,\n} from '../../utils/typed-map.js'\nimport { zUint8Array } from '../../utils/zod.js'\nimport { CwtClaimVerificationError } from '../error.js'\nimport { RegisteredCwtClaimKey } from './default.js'\n\n/**\n * A CWT NumericDate: the number of seconds since the epoch, as an integer or a floating-point\n * number.\n *\n * @see https://www.rfc-editor.org/rfc/rfc8392#section-2\n */\nexport const zCwtNumericDate = z.number()\n\n/**\n * The registered CWT claims (RFC 8392 Section 3.1), as `typedMap` entries.\n *\n * All of them are optional: RFC 8392 does not require any claim to be present, and which claims a\n * token must carry is decided by the CWT type. A specific CWT builds on these with\n * {@link extendCwtPayloadClaims}, and can make a claim required by redeclaring it.\n */\nexport const cwtPayloadClaimEntries = [\n [RegisteredCwtClaimKey.Issuer, z.string().exactOptional()],\n [RegisteredCwtClaimKey.Subject, z.string().exactOptional()],\n // RFC 8392 defines `aud` as a single StringOrURI, but tokens in the wild follow JWT and also use\n // an array, so both are accepted.\n [RegisteredCwtClaimKey.Audience, z.union([z.string(), z.array(z.string())]).exactOptional()],\n [RegisteredCwtClaimKey.ExpirationTime, zCwtNumericDate.exactOptional()],\n [RegisteredCwtClaimKey.NotBefore, zCwtNumericDate.exactOptional()],\n [RegisteredCwtClaimKey.IssuedAt, zCwtNumericDate.exactOptional()],\n [RegisteredCwtClaimKey.CwtId, zUint8Array.exactOptional()],\n] as const\n\n/**\n * Schema for a CWT Claims Set carrying only the registered claims. Additional (application or\n * private use) claims are allowed through untyped.\n */\nexport const cwtPayloadSchema = typedMap(cwtPayloadClaimEntries, {\n allowAdditionalKeys: true,\n keyLabels: RegisteredCwtClaimKey,\n})\n\nexport type ExtendedCwtPayloadClaimEntries<Entries extends EntriesBase> = ExtendedEntries<\n typeof cwtPayloadClaimEntries,\n Entries\n>\n\n/**\n * Builds a claims schema for a specific CWT type: the registered CWT claims plus the given ones. An\n * entry reusing a registered claim key replaces it, which is how a CWT type makes an inherited claim\n * required or narrows its value.\n *\n * The registered claim names are used in validation errors out of the box. Pass `keyLabels` to name\n * the added claims too — a numeric TypeScript enum can be passed straight in.\n *\n * @example\n * ```ts\n * const statusListCwtPayloadSchema = extendCwtPayloadClaims(\n * [\n * // `sub` is optional in the registered claims, but required for a status list\n * [RegisteredCwtClaimKey.Subject, z.string()],\n * [StatusListCwtClaimKey.StatusList, z.instanceof(StatusListCbor)],\n * ] as const,\n * { keyLabels: StatusListCwtClaimKey }\n * )\n * ```\n */\nexport function extendCwtPayloadClaims<const Entries extends EntriesBase>(\n entries: Entries,\n {\n keyLabels,\n }: {\n /**\n * Human-readable names for the added claims, merged with the registered CWT claim names. See\n * the `keyLabels` option of `typedMap`.\n */\n keyLabels?: Record<string | number, unknown>\n } = {}\n): ReturnType<typeof typedMap<ExtendedCwtPayloadClaimEntries<Entries>>> {\n return typedMap(extendTypedMapEntries(cwtPayloadClaimEntries, entries), {\n allowAdditionalKeys: true,\n keyLabels: { ...RegisteredCwtClaimKey, ...keyLabels },\n })\n}\n\nexport type CwtPayloadEncodedStructure = z.input<typeof cwtPayloadSchema>\nexport type CwtPayloadDecodedStructure = z.output<typeof cwtPayloadSchema>\n\nexport type CreateCwtPayloadOptions = {\n issuer?: string\n subject?: string\n audience?: string | string[]\n expirationTime?: Date\n notBefore?: Date\n issuedAt?: Date\n cwtId?: Uint8Array\n\n /**\n * Claims that are not part of the registered CWT claims. Added after the registered claims, in\n * iteration order.\n */\n additionalClaims?: Map<number | string, unknown>\n}\n\n/**\n * Builds the claims map for the registered CWT claims from {@link CreateCwtPayloadOptions}, so a CWT\n * type can reuse it while adding its own claims. Claims that were not provided are omitted rather\n * than set to `undefined`, since an explicit `undefined` would be encoded into the CBOR map.\n */\nexport function cwtPayloadClaimsFromOptions(options: CreateCwtPayloadOptions): Map<number | string, unknown> {\n const claims = new Map<number | string, unknown>()\n\n if (options.issuer !== undefined) claims.set(RegisteredCwtClaimKey.Issuer, options.issuer)\n if (options.subject !== undefined) claims.set(RegisteredCwtClaimKey.Subject, options.subject)\n if (options.audience !== undefined) claims.set(RegisteredCwtClaimKey.Audience, options.audience)\n if (options.expirationTime !== undefined) {\n claims.set(RegisteredCwtClaimKey.ExpirationTime, dateToSeconds(options.expirationTime))\n }\n if (options.notBefore !== undefined) claims.set(RegisteredCwtClaimKey.NotBefore, dateToSeconds(options.notBefore))\n if (options.issuedAt !== undefined) claims.set(RegisteredCwtClaimKey.IssuedAt, dateToSeconds(options.issuedAt))\n if (options.cwtId !== undefined) claims.set(RegisteredCwtClaimKey.CwtId, options.cwtId)\n\n for (const [key, value] of options.additionalClaims ?? new Map()) {\n claims.set(key, value)\n }\n\n return claims\n}\n\n/**\n * Names a claim for an error message, the same way a claims schema names it in a validation error:\n * `'Subject (2)'` for a registered claim, and the bare label for any other unless `keyLabels` has a\n * name for it.\n *\n * @see the `keyLabels` option of `typedMap`\n */\nexport function claimLabel(key: number | string, keyLabels?: Record<string | number, unknown>): string {\n return `'${keyLabel(key, { ...RegisteredCwtClaimKey, ...keyLabels })}'`\n}\n\n/** The options {@link CwtPayload.verifyClaims} takes. */\nexport type VerifyCwtClaimsOptions = {\n /** The time the token is verified at. Defaults to the current time. */\n now?: Date\n\n /**\n * Clock tolerance applied to `exp`, `nbf` and `iat`, in seconds. Defaults to 30, which keeps a\n * token that only just expired — or that was issued a moment ago by a slightly fast clock —\n * usable across the small clock differences typical between issuer and verifier.\n */\n skewSeconds?: number\n\n /**\n * The claims that must be present. A claim listed here is rejected when absent; a claim that is\n * absent and not listed is simply not checked. Any claim key can be required, not only a\n * registered one, since presence is checked against the claims map.\n */\n requiredClaims?: ReadonlyArray<RegisteredCwtClaimKey | number | string>\n\n /** The value(s) `iss` (1) is accepted with. Not checked when the token carries no `iss`. */\n expectedIssuer?: string | string[]\n\n /** The value(s) `sub` (2) is accepted with. Not checked when the token carries no `sub`. */\n expectedSubject?: string | string[]\n\n /**\n * The value(s) `aud` (3) is accepted with. The token is accepted when any of its audiences is\n * one of these. Not checked when the token carries no `aud`.\n */\n expectedAudience?: string | string[]\n\n /** When false, `exp` is not compared against `now`. Its presence is still checked. */\n checkExpirationTime?: boolean\n\n /** When false, `nbf` is not compared against `now`. Its presence is still checked. */\n checkNotBefore?: boolean\n\n /** When false, `iat` is not compared against `now`. Its presence is still checked. */\n checkIssuedAt?: boolean\n\n /**\n * Human-readable names for the claim keys, used in errors so that a bare CBOR label is not all a\n * reader gets. The registered CWT claim names are always available; pass the ones a CWT type adds\n * on top of them, the same way a claims schema is given them.\n *\n * @see the `keyLabels` option of `typedMap`\n */\n keyLabels?: Record<string | number, unknown>\n}\n\nconst asArray = (value: string | string[]) => (Array.isArray(value) ? value : [value])\nconst quoted = (values: string[]) => values.map((value) => `'${value}'`).join(', ')\n\n// biome-ignore lint/suspicious/noExplicitAny: inferring from an unconstrained TypedMap\ntype ClaimsSchemaOf<Structure> = Structure extends TypedMap<infer Schema, any> ? Schema : never\n// biome-ignore lint/suspicious/noExplicitAny: inferring from an unconstrained TypedMap\ntype OptionalClaimKeysOf<Structure> = Structure extends TypedMap<any, infer Optional> ? Optional : never\n\n/**\n * The shape a registered CWT claim always has, taken from the registered claims schema itself, and\n * `unknown` for any other claim key. Widened with `undefined`, since a registered claim is optional\n * unless the CWT type redeclares it as required.\n *\n * Every claims schema is built on `cwtPayloadClaimEntries`, so a registered claim is validated to\n * this shape whether or not the CWT type redeclares it. {@link ClaimValue} intersects it with the\n * type the CWT type's own schema gives the claim, which is what lets this class read its registered\n * claims while `Structure` is still generic: the schema's type is unresolved until `Structure` is\n * known, but the registered shape is not.\n */\ntype RegisteredClaimShape<Key extends number | string> = Key extends keyof ClaimsSchemaOf<CwtPayloadDecodedStructure>\n ? ClaimsSchemaOf<CwtPayloadDecodedStructure>[Key] | undefined\n : unknown\n\n/**\n * The value type of a single claim in a claims map: the schema's type for a claim the CWT type\n * declares (widened with `undefined` when it declares it as optional), and `unknown` for any other\n * claim key, since those are carried through unvalidated.\n *\n * Intersected with {@link RegisteredClaimShape}, which narrows nothing for a resolved schema —\n * `string & (string | undefined)` is `string` — and carries the registered shape through while\n * `Structure` is generic.\n */\nexport type ClaimValue<Structure, Key extends number | string> = RegisteredClaimShape<Key> &\n (Key extends keyof ClaimsSchemaOf<Structure>\n ? Key extends OptionalClaimKeysOf<Structure>\n ? ClaimsSchemaOf<Structure>[Key] | undefined\n : ClaimsSchemaOf<Structure>[Key]\n : unknown)\n\n/**\n * The type of a date accessor for a NumericDate claim: `Date` when the CWT type declares the claim\n * as required, and `Date | undefined` otherwise (including for a claim the type does not declare,\n * whose value is `unknown`). This is what makes the inherited date accessors narrow automatically in\n * a subtype that redeclares the claim as required.\n */\nexport type DateClaimValue<Structure, Key extends number | string> =\n undefined extends ClaimValue<Structure, Key> ? Date | undefined : Date\n\n/**\n * A CWT Claims Set (RFC 8392), with the registered claims typed.\n *\n * A specific CWT type extends this class and overrides {@link encodingSchema} with a schema built by\n * {@link extendCwtPayloadClaims}, passing the resulting decoded structure as `Structure`. The\n * inherited accessors then narrow along with the schema: a claim the subtype declares as required is\n * no longer `undefined`, neither on `claims.get(...)` nor on the accessor for it.\n *\n * @template Structure - The decoded claims map. Defaults to the registered CWT claims.\n */\nexport class CwtPayload<Structure extends AnyTypedMap = CwtPayloadDecodedStructure> extends CborStructure<\n CwtPayloadEncodedStructure,\n Structure\n> {\n // NOTE: widened to `z.ZodType` so a subtype can override it with its own (structurally unrelated)\n // claims schema without breaking static-side assignability.\n public static override get encodingSchema(): z.ZodType {\n return cwtPayloadSchema\n }\n\n /**\n * The decoded claims map. Typed for the claims this CWT type declares, and open for any other\n * claim key.\n */\n public get claims(): Structure {\n return this.structure\n }\n\n /**\n * Reads a claim by its key, typed from this CWT type's claims schema. A claim the schema does not\n * declare is returned as `unknown`, as it was carried through unvalidated.\n */\n public getClaim<Key extends number | string>(key: Key): ClaimValue<Structure, Key> {\n return this.structure.get(key) as ClaimValue<Structure, Key>\n }\n\n /** `iss` (1) */\n public get issuer(): ClaimValue<Structure, RegisteredCwtClaimKey.Issuer> {\n return this.getClaim(RegisteredCwtClaimKey.Issuer)\n }\n\n /** `sub` (2) */\n public get subject(): ClaimValue<Structure, RegisteredCwtClaimKey.Subject> {\n return this.getClaim(RegisteredCwtClaimKey.Subject)\n }\n\n /** `aud` (3) */\n public get audience(): ClaimValue<Structure, RegisteredCwtClaimKey.Audience> {\n return this.getClaim(RegisteredCwtClaimKey.Audience)\n }\n\n /** `exp` (4) */\n public get expirationTime(): DateClaimValue<Structure, RegisteredCwtClaimKey.ExpirationTime> {\n const expirationTime = this.getClaim(RegisteredCwtClaimKey.ExpirationTime)\n return (typeof expirationTime === 'number' ? secondsToDate(expirationTime) : undefined) as DateClaimValue<\n Structure,\n RegisteredCwtClaimKey.ExpirationTime\n >\n }\n\n /** `nbf` (5) */\n public get notBefore(): DateClaimValue<Structure, RegisteredCwtClaimKey.NotBefore> {\n const notBefore = this.getClaim(RegisteredCwtClaimKey.NotBefore)\n return (typeof notBefore === 'number' ? secondsToDate(notBefore) : undefined) as DateClaimValue<\n Structure,\n RegisteredCwtClaimKey.NotBefore\n >\n }\n\n /** `iat` (6) */\n public get issuedAt(): DateClaimValue<Structure, RegisteredCwtClaimKey.IssuedAt> {\n const issuedAt = this.getClaim(RegisteredCwtClaimKey.IssuedAt)\n return (typeof issuedAt === 'number' ? secondsToDate(issuedAt) : undefined) as DateClaimValue<\n Structure,\n RegisteredCwtClaimKey.IssuedAt\n >\n }\n\n /** `cti` (7) */\n public get cwtId(): ClaimValue<Structure, RegisteredCwtClaimKey.CwtId> {\n return this.getClaim(RegisteredCwtClaimKey.CwtId)\n }\n\n /**\n * Verifies this claims set: that the claims the CWT type requires are present, that `iss` / `sub`\n * / `aud` are the expected ones, and that the token is within its validity window (`exp`, `nbf`\n * and `iat`, compared against `now` with a clock skew tolerance).\n *\n * Which claims a CWT must carry and what they must contain is decided by the CWT type, not by\n * RFC 8392, so nothing is required unless `requiredClaims` says so. A CWT type overrides this\n * method to apply its own rules, and calls `super.verifyClaims` with them.\n *\n * This checks the claims only. The signature or authentication tag over them is verified\n * separately — `Cwt.verify` does both.\n *\n * @throws CwtClaimVerificationError if a required claim is missing, a claim does not match what\n * was expected, or the token is outside its validity window.\n *\n * @see https://www.rfc-editor.org/rfc/rfc8392#section-3.1\n */\n public verifyClaims({\n now = new Date(),\n skewSeconds = 30,\n requiredClaims,\n expectedIssuer,\n expectedSubject,\n expectedAudience,\n checkExpirationTime = true,\n checkNotBefore = true,\n checkIssuedAt = true,\n keyLabels,\n }: VerifyCwtClaimsOptions = {}): void {\n const skewMs = skewSeconds * 1000\n\n // Presence is checked against the claims map rather than against the accessors, so that a claim\n // this CWT type adds — which has no accessor here — can be required too.\n for (const key of requiredClaims ?? []) {\n if (!this.structure.has(key)) {\n throw new CwtClaimVerificationError(`The token has no ${claimLabel(key, keyLabels)} claim, which is required`)\n }\n }\n\n verifyClaimMatches(RegisteredCwtClaimKey.Issuer, this.issuer, expectedIssuer, keyLabels)\n verifyClaimMatches(RegisteredCwtClaimKey.Subject, this.subject, expectedSubject, keyLabels)\n verifyAudienceMatches(this.audience, expectedAudience, keyLabels)\n\n // `exp` is the first instant the token is no longer valid, so it is an upper bound shifted\n // forward by the skew: a token that expired within the tolerance is still accepted.\n const expirationTime: Date | undefined = this.expirationTime\n if (expirationTime !== undefined && checkExpirationTime && new Date(expirationTime.getTime() + skewMs) <= now) {\n throw new CwtClaimVerificationError(\n `The ${claimLabel(RegisteredCwtClaimKey.ExpirationTime, keyLabels)} claim '${expirationTime.toISOString()}' is in the past (compared to '${now.toISOString()}'), and therefore not valid`\n )\n }\n\n if (checkNotBefore) {\n verifyClaimNotInFuture(RegisteredCwtClaimKey.NotBefore, this.notBefore, now, skewMs, keyLabels)\n }\n if (checkIssuedAt) {\n verifyClaimNotInFuture(RegisteredCwtClaimKey.IssuedAt, this.issuedAt, now, skewMs, keyLabels)\n }\n }\n\n public static create(options: CreateCwtPayloadOptions = {}) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(TypedMap.fromMap(cwtPayloadClaimsFromOptions(options)))\n }\n}\n\nfunction verifyClaimMatches(\n key: RegisteredCwtClaimKey,\n value: string | undefined,\n expected: string | string[] | undefined,\n keyLabels?: Record<string | number, unknown>\n) {\n if (value === undefined || expected === undefined) return\n\n const expectedValues = asArray(expected)\n if (!expectedValues.includes(value)) {\n throw new CwtClaimVerificationError(\n `The ${claimLabel(key, keyLabels)} claim '${value}' does not match the expected value ${quoted(expectedValues)}`\n )\n }\n}\n\n/** `aud` may hold several audiences, and the token is for us as soon as one of them is expected. */\nfunction verifyAudienceMatches(\n audience: string | string[] | undefined,\n expected: string | string[] | undefined,\n keyLabels?: Record<string | number, unknown>\n) {\n if (audience === undefined || expected === undefined) return\n\n const audiences = asArray(audience)\n const expectedValues = asArray(expected)\n\n if (!audiences.some((value) => expectedValues.includes(value))) {\n throw new CwtClaimVerificationError(\n `The ${claimLabel(RegisteredCwtClaimKey.Audience, keyLabels)} claim ${quoted(audiences)} does not match the expected value ${quoted(expectedValues)}`\n )\n }\n}\n\n/**\n * `nbf` and `iat` are lower bounds on the validity window, so they are shifted back by the skew: a\n * token whose validity starts within the tolerance is already accepted.\n */\nfunction verifyClaimNotInFuture(\n key: RegisteredCwtClaimKey,\n value: Date | undefined,\n now: Date,\n skewMs: number,\n keyLabels?: Record<string | number, unknown>\n) {\n if (value === undefined) return\n\n if (new Date(value.getTime() - skewMs) > now) {\n throw new CwtClaimVerificationError(\n `The ${claimLabel(key, keyLabels)} claim '${value.toISOString()}' is in the future (compared to '${now.toISOString()}'), and therefore not valid`\n )\n }\n}\n\n/**\n * A {@link CwtPayload} with any claims schema. Used as a generic bound, because `TypedMap` is\n * invariant in its schema and a subtype's claims map is therefore not assignable to the base one.\n */\n// biome-ignore lint/suspicious/noExplicitAny: intentionally unconstrained, used as a generic bound\nexport type AnyCwtPayload = CwtPayload<any>\n","/**\n *\n * Registered CWT header keys\n *\n */\nexport enum RegisteredCwtHeaderClaimKey {\n Algorithm = 1,\n Critical = 2,\n ContentType = 3,\n KeyId = 4,\n Iv = 5,\n PartialIv = 6,\n CounterSignature = 7,\n CounterSignature0 = 9,\n CounterSignatureV2 = 11,\n CounterSignature0V2 = 12,\n Typ = 16,\n X5Bag = 32,\n X5Chain = 33,\n X5T = 34,\n X5U = 35,\n}\n\nexport enum SignatureAlgorithm {\n EdDSA = -8,\n ES256 = -7,\n ES384 = -35,\n ES512 = -36,\n PS256 = -37,\n PS384 = -38,\n PS512 = -39,\n RS256 = -257,\n RS384 = -258,\n RS512 = -259,\n}\n\nexport enum MacAlgorithm {\n HS256 = 5,\n HS384 = 6,\n HS512 = 7,\n}\n\nexport enum EncryptionAlgorithm {\n A128GCM = 1,\n A192GCM = 2,\n A256GCM = 3,\n Direct = -6,\n}\n\nexport type DigestAlgorithm = 'SHA-256' | 'SHA-384' | 'SHA-512'\n","import z from 'zod'\nimport {\n type EntriesBase,\n type ExtendedEntries,\n extendTypedMapEntries,\n type TypedMap,\n typedMap,\n} from '../../utils/typed-map.js'\nimport { zUint8Array } from '../../utils/zod.js'\nimport { RegisteredCwtHeaderClaimKey } from './defaults.js'\n\n// A COSE label is an integer (registry) or a text string (private use).\nconst zCoseLabel = z.union([z.number(), z.string()])\n// COSE_X509: a single certificate (bstr) or a chain (array of bstr). Used by x5bag/x5chain.\nconst zCertOrChain = z.union([zUint8Array, z.array(zUint8Array)])\n\n/**\n * The known COSE header claims (RFC 9052 Section 3.1 / RFC 9360 / RFC 9596 / the IANA COSE Header\n * Parameters registry), as `typedMap` entries.\n *\n * Exported separately from {@link coseHeaderClaimsSchema} so a profile can build on them with\n * {@link extendCoseHeaderClaims}.\n */\nexport const coseHeaderClaimEntries = [\n [RegisteredCwtHeaderClaimKey.Algorithm, zCoseLabel.exactOptional()],\n [RegisteredCwtHeaderClaimKey.Critical, z.array(zCoseLabel).exactOptional()],\n [RegisteredCwtHeaderClaimKey.ContentType, zCoseLabel.exactOptional()],\n [RegisteredCwtHeaderClaimKey.KeyId, zUint8Array.exactOptional()],\n [RegisteredCwtHeaderClaimKey.Iv, zUint8Array.exactOptional()],\n [RegisteredCwtHeaderClaimKey.PartialIv, zUint8Array.exactOptional()],\n // RFC 9596: a media type as a text string, or a CoAP Content-Format integer.\n [RegisteredCwtHeaderClaimKey.Typ, zCoseLabel.exactOptional()],\n [RegisteredCwtHeaderClaimKey.X5Bag, zCertOrChain.exactOptional()],\n [RegisteredCwtHeaderClaimKey.X5Chain, zCertOrChain.exactOptional()],\n [RegisteredCwtHeaderClaimKey.X5T, z.array(z.unknown()).exactOptional()],\n [RegisteredCwtHeaderClaimKey.X5U, z.string().exactOptional()],\n] as const\n\n/**\n * Schema for the known COSE header claims. Shared by the protected and unprotected header\n * structures.\n *\n * Each registered label is typed to its CBOR shape; in particular `kid` (4) is a bstr (`Uint8Array`),\n * so a header carrying a `kid` whose value is not a bstr (e.g. a malformed `{ 4: undefined }`) is\n * rejected at decode for every Sign1-derived structure. Additional (unregistered or private-use)\n * labels are allowed through (`allowAdditionalKeys`).\n */\nexport const coseHeaderClaimsSchema = typedMap(coseHeaderClaimEntries, {\n allowAdditionalKeys: true,\n keyLabels: RegisteredCwtHeaderClaimKey,\n})\n\nexport type CoseHeaderClaims = z.infer<typeof coseHeaderClaimsSchema>\n\nexport type ExtendedCoseHeaderClaimEntries<Entries extends EntriesBase> = ExtendedEntries<\n typeof coseHeaderClaimEntries,\n Entries\n>\n\n/**\n * Builds a header claims schema for a specific COSE/CWT profile: the registered COSE header claims\n * plus the given ones. An entry reusing a registered label replaces it, so a profile can also\n * narrow an existing claim (e.g. requiring `typ` to be a specific media type).\n *\n * The registered header claim names are used in validation errors out of the box. Pass `keyLabels`\n * to name the added labels too — a numeric TypeScript enum can be passed straight in.\n *\n * @example\n * ```ts\n * const statusListHeaderClaimsSchema = extendCoseHeaderClaims([\n * [RegisteredCwtHeaderClaimKey.Typ, z.literal('application/statuslist+cwt')],\n * ] as const)\n * ```\n */\nexport function extendCoseHeaderClaims<const Entries extends EntriesBase>(\n entries: Entries,\n {\n keyLabels,\n }: {\n /**\n * Human-readable names for the added header labels, merged with the registered COSE header\n * claim names. See the `keyLabels` option of `typedMap`.\n */\n keyLabels?: Record<string | number, unknown>\n } = {}\n): ReturnType<typeof typedMap<ExtendedCoseHeaderClaimEntries<Entries>>> {\n return typedMap(extendTypedMapEntries(coseHeaderClaimEntries, entries), {\n allowAdditionalKeys: true,\n keyLabels: { ...RegisteredCwtHeaderClaimKey, ...keyLabels },\n })\n}\n\n// Widen a typed-map type to also allow access to any other integer label.\ntype OpenIntegerKeys<T> =\n T extends TypedMap<infer Schema, infer Optional> ? TypedMap<Schema & Record<number, unknown>, Optional> : never\n\n/**\n * Read/write view over a COSE header map: the typed claims above plus open access to any other\n * integer label, because COSE headers are open-ended (unregistered and private-use labels are valid).\n * The typed claims are still validated at decode by `coseHeaderClaimsSchema`; this view only governs\n * typed access.\n */\nexport type CoseHeaders = OpenIntegerKeys<CoseHeaderClaims>\n\n/**\n * The {@link CoseHeaders} view for a profile-specific header claims schema, i.e. one built with\n * {@link extendCoseHeaderClaims}.\n */\nexport type CoseHeadersFor<Schema extends z.ZodType> = OpenIntegerKeys<z.infer<Schema>>\n","import z from 'zod'\nimport {\n type AnyCborStructure,\n CborStructure,\n type CborStructureStaticThis,\n type EncodedStructureType,\n} from '../../cbor/cbor-structure.js'\nimport { cborDecode, cborEncode } from '../../cbor/parser.js'\nimport { type AnyTypedMap, TypedMap } from '../../utils/typed-map.js'\nimport { zUint8Array } from '../../utils/zod.js'\nimport { type CoseHeaders, coseHeaderClaimsSchema } from './header-claims.js'\n\n// Wire form: the header map is wrapped in a bstr (RFC 9052). `protectedHeadersDecodedStructure` is\n// the plain map carried inside that bstr, kept for backwards compatibility.\nexport const protectedHeadersEncodedStructure = zUint8Array\nexport const protectedHeadersDecodedStructure = z.map(z.number(), z.unknown())\n\nexport type ProtectedHeadersEncodedStructure = z.infer<typeof protectedHeadersEncodedStructure>\nexport type ProtectedHeadersDecodedStructure = z.infer<typeof coseHeaderClaimsSchema>\n\n/**\n * Wraps a header claims schema in the bstr the protected headers are carried in (RFC 9052), giving\n * the encoding schema for a {@link ProtectedHeaders} class.\n *\n * A profile subclasses `ProtectedHeaders` and overrides `encodingSchema` with this, passing a claims\n * schema built by `extendCoseHeaderClaims`. The headers are then validated against that schema\n * wherever the structure is built, the same way every other `CborStructure` validates itself.\n */\nexport function protectedHeadersSchema<ClaimsSchema extends z.ZodType>(\n claimsSchema: z.ZodCodec<z.ZodType, ClaimsSchema>\n) {\n return z.codec(protectedHeadersEncodedStructure, claimsSchema.out, {\n // TODO: Senders SHOULD encode a zero-length map as a zero-length string rather than as a zero-length map\n encode: (decoded) => cborEncode((decoded as AnyTypedMap).toMap()) as Uint8Array<ArrayBuffer>,\n decode: (encoded) =>\n TypedMap.fromMap(cborDecode(encoded) as Map<number, unknown>) as unknown as z.input<ClaimsSchema>,\n })\n}\n\nexport type ProtectedHeaderOptions = {\n protectedHeaders?: Map<number, unknown>\n}\n\n/**\n * The protected header map of a COSE structure.\n *\n * A profile that adds or narrows header labels subclasses this and overrides `encodingSchema` with\n * `protectedHeadersSchema(...)`, passing the type of the resulting map as `Headers`:\n *\n * ```ts\n * const claims = extendCoseHeaderClaims([[RegisteredCwtHeaderClaimKey.Typ, z.literal('application/example+cwt')]] as const)\n *\n * class ExampleProtectedHeaders extends ProtectedHeaders<CoseHeadersFor<typeof claims>> {\n * public static override get encodingSchema() {\n * return protectedHeadersSchema(claims)\n * }\n * }\n * ```\n *\n * Headers decoded from a token keep the bstr they came from, so that verification uses the bytes the\n * issuer signed rather than our re-encoding of them. See {@link originalEncodedStructure}.\n *\n * @template Headers - The typed view over the header map. Defaults to the registered COSE header\n * claims.\n */\nexport class ProtectedHeaders<Headers extends AnyTypedMap = CoseHeaders> extends CborStructure<\n ProtectedHeadersEncodedStructure,\n Headers\n> {\n /**\n * The bstr this was decoded from, kept so that it is what goes back into the `Sig_structure` /\n * `MAC_structure` (RFC 9052 puts the protected headers in as an opaque bstr, so what was signed\n * is the exact bytes the issuer sent). Re-encoding the map instead is not byte-preserving for\n * input that is valid CBOR but not the form we would write — a non-shortest-form integer, an\n * indefinite-length map, a float, a bignum, a tag 0 date — and the signature over such a token\n * would fail to verify for no visible reason.\n *\n * Dropped as soon as the header map is changed, since the bytes no longer describe it.\n *\n * @see https://datatracker.ietf.org/doc/rfc9052/#section-4.4\n */\n private originalEncodedStructure?: ProtectedHeadersEncodedStructure\n\n public static override get encodingSchema(): z.ZodType {\n return protectedHeadersSchema(coseHeaderClaimsSchema)\n }\n\n public get headers(): Headers {\n return this.structure\n }\n\n /**\n * The header map as it goes on the wire: the bstr this was decoded from when it came from a\n * token and has not been changed since, and the encoded map otherwise.\n */\n public override get encodedStructure(): ProtectedHeadersEncodedStructure {\n return this.originalEncodedStructure ?? super.encodedStructure\n }\n\n /**\n * Drops the retained {@link originalEncodedStructure}, so that the headers are re-encoded the next\n * time they are used. Changing the header map does this on its own; call it after changing a\n * header *value* in place — `headers.get(x5chain)[0] = ...` — which the map cannot see.\n */\n public markModified() {\n this.originalEncodedStructure = undefined\n }\n\n public static override fromEncodedStructure<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n encodedStructure: EncodedStructureType<T>\n ): T {\n // biome-ignore lint/complexity/noThisInStatic: `super` keeps `this` bound to the subclass it was called on, which is what constructs a profile's header class rather than this one\n const headers = super.fromEncodedStructure(encodedStructure) as T & ProtectedHeaders<AnyTypedMap>\n\n // NOTE: copied, because the decoder hands back a view onto the buffer the whole token was\n // decoded from.\n headers.originalEncodedStructure = new Uint8Array(encodedStructure as Uint8Array)\n headers.headers.onChange = () => headers.markModified()\n\n return headers\n }\n\n public static create(options: ProtectedHeaderOptions) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(TypedMap.fromMap(options.protectedHeaders ?? new Map()))\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport { type AnyTypedMap, TypedMap } from '../../utils/typed-map.js'\nimport { type CoseHeaders, coseHeaderClaimsSchema } from './header-claims.js'\n\n// Wire form: a plain map of integer label -> value (used by the COSE_Sign1 encoded schema).\nexport const unprotectedHeadersStructure = z.map(z.number(), z.unknown())\n\nexport type UnprotectedHeadersEncodedStructure = z.infer<typeof unprotectedHeadersStructure>\nexport type UnprotectedHeadersDecodedStructure = z.infer<typeof coseHeaderClaimsSchema>\n\n// Backwards-compatible alias for the wire structure.\nexport type UnprotectedHeadersStructure = UnprotectedHeadersEncodedStructure\n\nexport type UnprotectedHeaderOptions = {\n unprotectedHeaders?: UnprotectedHeadersEncodedStructure\n}\n\n/**\n * The unprotected header map of a COSE structure. Subclassed the same way as\n * {@link ProtectedHeaders}, except that the claims schema is the encoding schema directly, since\n * the unprotected headers are carried as a plain map rather than wrapped in a bstr.\n *\n * @template Headers - The typed view over the header map. See {@link ProtectedHeaders}.\n */\nexport class UnprotectedHeaders<Headers extends AnyTypedMap = CoseHeaders> extends CborStructure<\n UnprotectedHeadersEncodedStructure,\n Headers\n> {\n public static override get encodingSchema(): z.ZodType {\n return coseHeaderClaimsSchema\n }\n\n public get headers(): Headers {\n return this.structure\n }\n\n public static create(options: UnprotectedHeaderOptions) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(TypedMap.fromMap(options.unprotectedHeaders ?? new Map()))\n }\n}\n","import { compareBytes } from '@owf/identity-common'\nimport type { AnyTypedMap } from '../../utils/typed-map.js'\nimport { CoseX5ChainNotBoundError } from '../error.js'\nimport { type DigestAlgorithm, RegisteredCwtHeaderClaimKey } from './defaults.js'\nimport type { ProtectedHeaders } from './protected-headers.js'\nimport type { UnprotectedHeaders } from './unprotected-headers.js'\n\n/** SHA-256 in a COSE_CertHash (RFC 9360), as registered in RFC 9054. */\nconst COSE_SHA_256 = -16\n\nexport type X5ChainContext = {\n digest: (input: { digestAlgorithm: DigestAlgorithm; bytes: Uint8Array }) => Promise<Uint8Array> | Uint8Array\n}\n\n/**\n * The `x5chain` of a COSE structure, provided its end-entity certificate is integrity protected, as\n * RFC 9360 requires: read from the protected header, or else from the unprotected header when a\n * protected `x5t` matches its leaf. The unprotected header is not covered by the signature, so\n * without that binding the certificate could be replaced by another one for the same key.\n *\n * Only a SHA-256 `x5t` is supported.\n *\n * @returns the chain, leaf first, or `undefined` when neither header has an `x5chain`.\n * @throws CoseX5ChainNotBoundError if the `x5chain` is in the unprotected header but no protected `x5t` matches its leaf.\n */\nexport async function getIntegrityProtectedX5Chain(\n {\n protectedHeaders,\n unprotectedHeaders,\n }: { protectedHeaders: ProtectedHeaders<AnyTypedMap>; unprotectedHeaders: UnprotectedHeaders<AnyTypedMap> },\n ctx: X5ChainContext\n): Promise<Array<Uint8Array> | undefined> {\n const protectedX5Chain = normalizeX5Chain(protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.X5Chain))\n if (protectedX5Chain) return protectedX5Chain\n\n const x5chain = normalizeX5Chain(unprotectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.X5Chain))\n if (!x5chain) return undefined\n\n const x5t = protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.X5T)\n if (!Array.isArray(x5t) || x5t.length !== 2 || !(x5t[1] instanceof Uint8Array)) {\n throw new CoseX5ChainNotBoundError(\n 'The x5chain is in the unprotected header, but the protected header has no x5t that binds it'\n )\n }\n\n const [hashAlgorithm, expectedHash] = x5t as [unknown, Uint8Array]\n if (hashAlgorithm !== COSE_SHA_256) {\n throw new CoseX5ChainNotBoundError(\n `The x5t of the protected header uses hash algorithm '${String(hashAlgorithm)}', only SHA-256 (-16) is supported`\n )\n }\n\n const leafHash = await ctx.digest({ digestAlgorithm: 'SHA-256', bytes: x5chain[0] })\n if (!compareBytes(leafHash, expectedHash)) {\n throw new CoseX5ChainNotBoundError(\n 'The x5t of the protected header does not match the leaf of the x5chain in the unprotected header'\n )\n }\n\n return x5chain\n}\n\n/** COSE_X509 carries either a single certificate or a chain of them (RFC 9360). */\nfunction normalizeX5Chain(x5chain: unknown): Array<Uint8Array> | undefined {\n const chain = x5chain instanceof Uint8Array ? [x5chain] : x5chain\n if (!Array.isArray(chain) || chain.length === 0 || !chain.every((c) => c instanceof Uint8Array)) return undefined\n return chain\n}\n","export enum Curve {\n 'P-256' = 1,\n 'P-384' = 2,\n 'P-521' = 3,\n X25519 = 4,\n X448 = 5,\n Ed25519 = 6,\n Ed448 = 7,\n}\n","export enum KeyOps {\n Sign = 1,\n Verify = 2,\n Encrypt = 3,\n Decrypt = 4,\n WrapKey = 5,\n UnwrapKey = 6,\n DeriveKey = 7,\n DeriveBits = 8,\n MACCreate = 9,\n MACVerify = 10,\n}\n","export enum KeyType {\n Okp = 1,\n Ec = 2,\n Oct = 4,\n Reserved = 0,\n}\n","import { base64url } from '@owf/identity-common'\nimport { EncryptionAlgorithm, MacAlgorithm, SignatureAlgorithm } from '../headers/defaults'\nimport { Curve } from './curve'\nimport type { CoseKeyOptions } from './key'\nimport { KeyOps } from './key-operation'\nimport { KeyType } from './key-type'\n\nconst swapMap = (map: Record<string, string>) =>\n Object.fromEntries(Object.entries(map).map(([key, value]) => [value, key]))\n\nconst swapNestedMap = (nestedMap: Record<string, Record<string, unknown>>) =>\n Object.fromEntries(\n Object.entries(nestedMap).map(([category, mappings]) => [\n category,\n Object.fromEntries(Object.entries(mappings).map(([key, value]) => [value, key])),\n ])\n )\n\nconst jwkCoseKeyMap = {\n kty: {\n OKP: KeyType.Okp,\n EC: KeyType.Ec,\n OCT: KeyType.Oct,\n },\n crv: {\n 'P-256': Curve['P-256'],\n 'P-384': Curve['P-384'],\n 'P-521': Curve['P-521'],\n X25519: Curve.X25519,\n Ed25519: Curve.Ed25519,\n Ed448: Curve.Ed448,\n },\n alg: {\n EdDSA: SignatureAlgorithm.EdDSA,\n ES256: SignatureAlgorithm.ES256,\n ES384: SignatureAlgorithm.ES384,\n ES512: SignatureAlgorithm.ES512,\n PS256: SignatureAlgorithm.PS256,\n PS384: SignatureAlgorithm.PS384,\n PS512: SignatureAlgorithm.PS512,\n RS256: SignatureAlgorithm.RS256,\n RS384: SignatureAlgorithm.RS384,\n RS512: SignatureAlgorithm.RS512,\n\n HS256: MacAlgorithm.HS256,\n HS384: MacAlgorithm.HS384,\n HS512: MacAlgorithm.HS512,\n\n A128GCM: EncryptionAlgorithm.A128GCM,\n A192GCM: EncryptionAlgorithm.A192GCM,\n A256GCM: EncryptionAlgorithm.A256GCM,\n Direct: EncryptionAlgorithm.Direct,\n },\n keyOps: {\n sign: KeyOps.Sign,\n verify: KeyOps.Verify,\n encrypt: KeyOps.Encrypt,\n decrypt: KeyOps.Decrypt,\n wrapKey: KeyOps.WrapKey,\n unwrapKey: KeyOps.UnwrapKey,\n deriveKey: KeyOps.DeriveKey,\n deriveBits: KeyOps.DeriveBits,\n mACCreate: KeyOps.MACCreate,\n mACVerify: KeyOps.MACVerify,\n },\n}\n\nconst coseKeyJwkMap = swapNestedMap(jwkCoseKeyMap)\n\nexport const jwkCoseOptionsMap: Record<string, keyof CoseKeyOptions> = {\n kty: 'keyType',\n kid: 'keyId',\n alg: 'algorithm',\n keyOps: 'keyOps',\n baseIv: 'baseIv',\n crv: 'curve',\n x: 'x',\n y: 'y',\n d: 'd',\n k: 'k',\n}\n\nexport const coseOptionsJwkMap = swapMap(jwkCoseOptionsMap)\n\nexport const jwkToCoseKey = {\n kty: (kty?: unknown) =>\n jwkCoseKeyMap.kty[(kty as string).toUpperCase() as keyof (typeof jwkCoseKeyMap)['kty']] ?? kty,\n crv: (crv?: unknown) => jwkCoseKeyMap.crv[crv as keyof (typeof jwkCoseKeyMap)['crv']] ?? crv,\n alg: (alg?: unknown) => jwkCoseKeyMap.alg[alg as keyof (typeof jwkCoseKeyMap)['alg']] ?? alg,\n kid: (kid?: unknown) => kid,\n keyOps: (keyOps?: unknown) =>\n Array.isArray(keyOps)\n ? keyOps?.map((ko) => jwkCoseKeyMap.keyOps[ko as keyof (typeof jwkCoseKeyMap)['keyOps']] ?? ko)\n : undefined,\n x: (s?: unknown) => (s && typeof s === 'string' ? base64url.decode(s) : undefined),\n y: (s?: unknown) => (s && typeof s === 'string' ? base64url.decode(s) : undefined),\n d: (s?: unknown) => (s && typeof s === 'string' ? base64url.decode(s) : undefined),\n k: (s?: unknown) => (s && typeof s === 'string' ? base64url.decode(s) : undefined),\n}\n\nexport const coseKeyToJwkClaim = {\n keyType: (keyType: KeyType) => coseKeyJwkMap.kty[keyType],\n keyId: (keyId: unknown) => keyId,\n algorithm: (algorithm?: SignatureAlgorithm | MacAlgorithm) => (algorithm ? coseKeyJwkMap.alg[algorithm] : undefined),\n keyOps: (keyOps?: unknown) =>\n keyOps && Array.isArray(keyOps) ? keyOps.map((ko) => coseKeyJwkMap.keyOps[ko]) : undefined,\n baseIv: (baseIv?: unknown) => baseIv,\n curve: (curve?: Curve) => (curve ? coseKeyJwkMap.crv[curve] : undefined),\n x: (x?: Uint8Array) => (x ? base64url.encode(x) : undefined),\n y: (y?: Uint8Array) => (y ? base64url.encode(y) : undefined),\n d: (d?: Uint8Array) => (d ? base64url.encode(d) : undefined),\n k: (k?: Uint8Array) => (k ? base64url.encode(k) : undefined),\n}\n","import { bytesToString, concatBytes, stringToBytes } from '@owf/identity-common'\nimport { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { TypedMap, typedMap } from '../../utils/typed-map'\nimport { zUint8Array } from '../../utils/zod'\nimport {\n CoseDNotDefinedError,\n CoseInvalidKtyForRawError,\n CoseInvalidValueForKtyError,\n CoseKeyTypeNotSupportedForPrivateKeyExtractionError,\n CoseKNotDefinedError,\n CoseXNotDefinedError,\n CoseYNotDefinedError,\n} from '../error'\nimport type { MacAlgorithm, SignatureAlgorithm } from '../headers'\nimport { Curve } from './curve'\nimport { coseKeyToJwkClaim, coseOptionsJwkMap, jwkCoseOptionsMap, jwkToCoseKey } from './jwk'\nimport { KeyOps } from './key-operation'\nimport { KeyType } from './key-type'\n\nexport enum CoseKeyParameter {\n KeyType = 1,\n KeyId = 2,\n Algorithm = 3,\n KeyOps = 4,\n BaseIv = 5,\n\n // EC Key or Oct with K\n CurveOrK = -1,\n X = -2,\n Y = -3,\n D = -4,\n}\n\n// Zod schema for CoseKey validation\nconst coseKeySchema = typedMap(\n [\n [CoseKeyParameter.KeyType, z.union([z.enum(KeyType), z.string()])],\n [\n CoseKeyParameter.KeyId,\n // NOTE: string is NOT allowed, but seems mDocs issued with v0.5 of this library\n // do include string keyIds. We need to ensure we don't break interop. For newly\n // created keys we ensure correct encoding.\n zUint8Array.or(z.string()).exactOptional(),\n ],\n [\n CoseKeyParameter.Algorithm,\n z\n .union([\n z.string({ error: 'Cose algorithm must be a string' }),\n z.number({ error: 'Cose algorithm must be a number' }),\n ])\n .exactOptional(),\n ],\n [CoseKeyParameter.KeyOps, z.array(z.union([z.enum(KeyOps), z.string()])).exactOptional()],\n [CoseKeyParameter.BaseIv, zUint8Array.exactOptional()],\n [CoseKeyParameter.CurveOrK, z.union([z.enum(Curve), zUint8Array]).exactOptional()],\n [CoseKeyParameter.X, zUint8Array.exactOptional()],\n [CoseKeyParameter.Y, zUint8Array.exactOptional()],\n [CoseKeyParameter.D, zUint8Array.exactOptional()],\n ] as const,\n { keyLabels: CoseKeyParameter }\n)\n\n// Infer structure type from Zod schema\nexport type CoseKeyDecodedStructure = z.output<typeof coseKeySchema>\nexport type CoseKeyEncodedStructure = z.input<typeof coseKeySchema>\n\n// Manual options type (user-facing API)\nexport type CoseKeyOptions = {\n keyType: KeyType | string\n keyId?: string\n algorithm?: string | number\n keyOps?: Array<KeyOps | string>\n baseIv?: Uint8Array\n\n curve?: Curve\n x?: Uint8Array\n y?: Uint8Array\n\n d?: Uint8Array\n\n k?: Uint8Array\n}\n\nexport class CoseKey extends CborStructure<CoseKeyEncodedStructure, CoseKeyDecodedStructure> {\n public static override get encodingSchema() {\n return coseKeySchema\n }\n\n public get keyType() {\n return this.structure.get(CoseKeyParameter.KeyType)\n }\n\n public get keyId() {\n const keyId = this.structure.get(CoseKeyParameter.KeyId)\n return keyId instanceof Uint8Array ? bytesToString(keyId) : keyId\n }\n\n public get algorithm() {\n return this.structure.get(CoseKeyParameter.Algorithm) as SignatureAlgorithm | MacAlgorithm | undefined\n }\n\n public get keyOps() {\n return this.structure.get(CoseKeyParameter.KeyOps)\n }\n\n public get baseIv() {\n return this.structure.get(CoseKeyParameter.BaseIv)\n }\n\n public get curve() {\n if (this.keyType === KeyType.Ec || this.keyType === KeyType.Okp) {\n // Casting is needed, as it can be both Curve or K\n return this.structure.get(CoseKeyParameter.CurveOrK) as Curve | undefined\n }\n\n return undefined\n }\n\n public get x() {\n return this.structure.get(CoseKeyParameter.X)\n }\n\n public get y() {\n return this.structure.get(CoseKeyParameter.Y)\n }\n\n public get d() {\n return this.structure.get(CoseKeyParameter.D)\n }\n\n public get k() {\n if (this.keyType === KeyType.Oct) {\n return this.structure.get(CoseKeyParameter.CurveOrK) as Uint8Array | undefined\n }\n return undefined\n }\n\n public static create(options: CoseKeyOptions) {\n const map: CoseKeyDecodedStructure = new TypedMap([[CoseKeyParameter.KeyType, options.keyType]])\n\n if (options.keyId !== undefined) {\n map.set(CoseKeyParameter.KeyId, stringToBytes(options.keyId))\n }\n\n if (options.algorithm !== undefined) {\n map.set(CoseKeyParameter.Algorithm, options.algorithm)\n }\n\n if (options.keyOps !== undefined) {\n map.set(CoseKeyParameter.KeyOps, options.keyOps)\n }\n\n if (options.baseIv !== undefined) {\n map.set(CoseKeyParameter.BaseIv, options.baseIv)\n }\n\n if (options.curve !== undefined) {\n map.set(CoseKeyParameter.CurveOrK, options.curve)\n }\n\n if (options.x !== undefined) {\n map.set(CoseKeyParameter.X, options.x)\n }\n\n if (options.y !== undefined) {\n map.set(CoseKeyParameter.Y, options.y)\n }\n\n if (options.d !== undefined) {\n map.set(CoseKeyParameter.D, options.d)\n }\n\n if (options.k !== undefined) {\n map.set(CoseKeyParameter.CurveOrK, options.k)\n }\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n\n // TODO: add jwk zod schema\n public static fromJwk(jwk: Record<string, unknown>) {\n if (!('kty' in jwk)) {\n throw new CoseInvalidValueForKtyError('JWK does not contain required kty value')\n }\n\n const options = Object.entries(jwk).reduce((prev, [key, value]) => {\n const mappedKey = jwkCoseOptionsMap[key] ?? key\n\n const mapFunction = jwkToCoseKey[key as keyof typeof jwkToCoseKey]\n const convertedValue = mapFunction ? mapFunction(value) : value\n\n // Only include if value is not undefined\n if (convertedValue !== undefined) {\n // biome-ignore lint/performance/noAccumulatingSpread: time-complexity is not relevant here\n return { ...prev, [mappedKey]: convertedValue }\n }\n\n return prev\n }, {} as CoseKeyOptions)\n\n // biome-ignore lint/complexity/noThisInStatic: this.create is intentional for subclass support\n return this.create(options)\n }\n\n public get publicKey() {\n if (this.keyType !== KeyType.Ec && this.keyType !== KeyType.Okp) {\n throw new CoseInvalidKtyForRawError()\n }\n\n if (!this.x) {\n throw new CoseXNotDefinedError()\n }\n\n if (this.keyType === KeyType.Okp) {\n return this.x\n }\n\n if (!this.y) {\n throw new CoseYNotDefinedError()\n }\n\n return concatBytes(Uint8Array.from([0x04]), this.x, this.y)\n }\n\n /**\n *\n * @returns the `d` value for `ec` and `okp` key types\n * @returns the `k` value for `oct` key types\n *\n */\n public get privateKey() {\n if (this.keyType === KeyType.Ec || this.keyType === KeyType.Okp) {\n if (!this.d) {\n throw new CoseDNotDefinedError()\n }\n\n return this.d\n }\n\n if (this.keyType === KeyType.Oct) {\n if (!this.k) {\n throw new CoseKNotDefinedError()\n }\n\n return this.k\n }\n\n throw new CoseKeyTypeNotSupportedForPrivateKeyExtractionError()\n }\n\n public get jwk(): Record<string, unknown> {\n // Convert CoseKey properties to JWK format\n const options: CoseKeyOptions = {\n keyType: this.keyType,\n keyId: this.keyId,\n algorithm: this.algorithm,\n keyOps: this.keyOps,\n baseIv: this.baseIv,\n curve: this.curve,\n x: this.x,\n y: this.y,\n d: this.d,\n k: this.k,\n }\n\n return Object.entries(options).reduce(\n (prev, [key, value]) => ({\n // biome-ignore lint/performance/noAccumulatingSpread: time-complexity is not relevant here\n ...prev,\n [coseOptionsJwkMap[key] ?? key]:\n typeof coseKeyToJwkClaim[key as keyof typeof coseKeyToJwkClaim] === 'function'\n ? // @ts-ignore\n coseKeyToJwkClaim[key as keyof typeof coseKeyToJwkClaim](value)\n : undefined,\n }),\n {}\n )\n }\n}\n","import { z } from 'zod'\nimport {\n type AnyCborStructure,\n addExtension,\n CborStructure,\n type CborStructureStaticThis,\n cborDecode,\n cborEncode,\n type EncodedStructureType,\n} from '../cbor'\nimport { zUint8Array } from '../utils/zod'\nimport { CoseInvalidAlgorithmError, CosePayloadMustBeDefinedError } from './error'\nimport { MacAlgorithm, RegisteredCwtHeaderClaimKey } from './headers/defaults'\nimport {\n type ProtectedHeaderOptions,\n ProtectedHeaders,\n type ProtectedHeadersEncodedStructure,\n} from './headers/protected-headers'\nimport {\n type UnprotectedHeaderOptions,\n UnprotectedHeaders,\n type UnprotectedHeadersStructure,\n} from './headers/unprotected-headers'\nimport { CoseKey } from './key'\nimport { coseKeyToJwkClaim } from './key/jwk'\n\nexport const mac0EncodedSchema = z.tuple([\n zUint8Array,\n z.map(z.unknown(), z.unknown()),\n zUint8Array.nullable(),\n zUint8Array,\n])\n\nexport const mac0DecodedSchema = z.object({\n protectedHeaders: z.instanceof(ProtectedHeaders),\n unprotectedHeaders: z.instanceof(UnprotectedHeaders),\n payload: zUint8Array.nullable(),\n tag: zUint8Array,\n})\n\nexport type Mac0EncodedStructure = z.infer<typeof mac0EncodedSchema>\nexport type Mac0DecodedStructure = z.infer<typeof mac0DecodedSchema>\n\nexport type Mac0Context = {\n authenticate: (options: {\n toBeAuthenticated: Uint8Array\n key: CoseKey | Uint8Array\n algorithm?: MacAlgorithm\n }) => Promise<Uint8Array>\n verify: (options: {\n toBeAuthenticated: Uint8Array\n tag: Uint8Array\n key: CoseKey | Uint8Array\n algorithm?: MacAlgorithm\n }) => Promise<boolean>\n}\n\nexport type Mac0Options = {\n protectedHeaders?: ProtectedHeaders | ProtectedHeaderOptions['protectedHeaders']\n unprotectedHeaders?: UnprotectedHeaders | UnprotectedHeaderOptions['unprotectedHeaders']\n\n /**\n * The embedded payload. Pass `null` to explicitly signal a detached payload\n * (the encoded structure will contain null, and you must supply the payload\n * via `detachedPayload` when calling `authenticate()` / `toBeAuthenticated()`).\n */\n payload: Uint8Array | null\n\n tag?: Uint8Array\n}\n\nexport class Mac0 extends CborStructure<Mac0EncodedStructure, Mac0DecodedStructure> {\n public static tag = 17\n protected override _tag = Mac0.tag\n\n public static override get encodingSchema() {\n return z.codec(mac0EncodedSchema, mac0DecodedSchema, {\n encode: ({ protectedHeaders, unprotectedHeaders, payload, tag }) => {\n if (tag.length === 0) {\n throw new Error('Tag has not been set. Required for encoding the mac0 structure')\n }\n return [\n protectedHeaders.encodedStructure,\n unprotectedHeaders.encodedStructure,\n payload,\n tag,\n ] satisfies Mac0EncodedStructure\n },\n decode: ([protectedHeadersBytes, unprotectedHeadersMap, payload, tag]) => ({\n protectedHeaders: ProtectedHeaders.fromEncodedStructure(\n protectedHeadersBytes as ProtectedHeadersEncodedStructure\n ),\n unprotectedHeaders: UnprotectedHeaders.fromEncodedStructure(\n unprotectedHeadersMap as UnprotectedHeadersStructure\n ),\n payload,\n tag,\n }),\n })\n }\n\n public get protectedHeaders() {\n return this.structure.protectedHeaders\n }\n\n public get unprotectedHeaders() {\n return this.structure.unprotectedHeaders\n }\n\n public get payload() {\n return this.structure.payload\n }\n\n public get tag() {\n return this.structure.tag\n }\n\n /**\n * Returns the MAC_Structure bytes that are authenticated/verified.\n *\n * @param options.detachedPayload - The detached payload to use. Must be provided when\n * the Mac0 was created with a detached payload (i.e. `payload` field is null).\n * Cannot be provided when the Mac0 already contains an embedded payload.\n * @param options.externalAad - Externally supplied data covered by the authentication tag. It is\n * not part of the COSE structure, so it has to be provided identically wherever the\n * MAC_Structure is built: `authenticate()`, `verifyAuthenticationCode()` and here.\n */\n public toBeAuthenticated(options?: { detachedPayload?: Uint8Array; externalAad?: Uint8Array }): Uint8Array {\n const embeddedPayload = this.payload\n const detachedPayload = options?.detachedPayload\n\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Mac0 already contains an embedded payload')\n }\n\n const payload = embeddedPayload ?? detachedPayload\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n return Mac0.toBeAuthenticated({\n payload,\n protectedHeaders: this.protectedHeaders,\n externalAad: options?.externalAad,\n })\n }\n\n /**\n * Decodes CBOR bytes into a Mac0 instance.\n * Uses the encodingSchema's decode() method to validate and transform the decoded data.\n */\n public static decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n const rawStructure = cborDecode(bytes)\n\n // May feel weird, but using new this makes TypeScript understand we may return a subclass\n return new this(\n // NOTE: If decoded with Mac0 tag, the cbor decoder already transforms to the class instances\n // In that case we create new instance based on the decoded structure, to ensure we create the\n // instance based on this (and ensure extended classes work)\n // biome-ignore lint/complexity/noThisInStatic: this check is intentional for subclass support\n rawStructure instanceof Mac0 && rawStructure.constructor === this\n ? rawStructure.decodedStructure\n : // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\n this.fromEncodedStructure(\n (rawStructure instanceof Mac0 ? rawStructure.encodedStructure : rawStructure) as EncodedStructureType<T>\n ).decodedStructure\n ) as unknown as T\n }\n\n public static toBeAuthenticated(options: {\n payload: Uint8Array\n protectedHeaders: ProtectedHeaders\n externalAad?: Uint8Array\n }) {\n const toBeAuthenticated = ['MAC0', options.protectedHeaders.encodedStructure]\n if (options.externalAad) toBeAuthenticated.push(options.externalAad)\n toBeAuthenticated.push(options.payload)\n\n return cborEncode(toBeAuthenticated)\n }\n\n public get algorithm(): MacAlgorithm | undefined {\n const algorithm = this.protectedHeaders.headers?.get(RegisteredCwtHeaderClaimKey.Algorithm) as\n | MacAlgorithm\n | undefined\n if (algorithm && !Object.values(MacAlgorithm).includes(algorithm)) {\n throw new CoseInvalidAlgorithmError()\n }\n\n return algorithm\n }\n\n public get jwaAlgorithm(): keyof typeof MacAlgorithm {\n const alg = this.algorithm\n\n const jwaAlg = coseKeyToJwkClaim.algorithm(alg)\n if (!jwaAlg) {\n throw new CoseInvalidAlgorithmError(`Cose algorithm ${alg} does not have a corresponding JWA alg`)\n }\n\n return jwaAlg\n }\n\n public static create(options: Mac0Options): Mac0 {\n const protectedHeaders =\n options.protectedHeaders instanceof ProtectedHeaders\n ? options.protectedHeaders\n : ProtectedHeaders.create({ protectedHeaders: options.protectedHeaders })\n\n const unprotectedHeaders =\n options.unprotectedHeaders instanceof UnprotectedHeaders\n ? options.unprotectedHeaders\n : UnprotectedHeaders.create({ unprotectedHeaders: options.unprotectedHeaders })\n\n const mac0 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n tag: options.tag ?? new Uint8Array(),\n })\n\n return mac0\n }\n\n public async authenticate(\n options: {\n key: CoseKey | Uint8Array\n detachedPayload?: Uint8Array\n algorithm?: MacAlgorithm\n externalAad?: Uint8Array\n },\n ctx: Pick<Mac0Context, 'authenticate'>\n ) {\n const embeddedPayload = this.payload\n const { detachedPayload } = options\n\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Mac0 already contains an embedded payload')\n }\n\n const payload = embeddedPayload ?? detachedPayload\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n // TODO: do we want to check whether key.algorithm and options.algorithm exist?\n const macAlgorithm = (options.key instanceof CoseKey ? options.key.algorithm : options.algorithm) as\n | MacAlgorithm\n | undefined\n\n if (!macAlgorithm) {\n throw new CoseInvalidAlgorithmError(\n 'Could not establish mac algorithm. Either provide it in the options directly, or provide it in the signingKey'\n )\n }\n\n if (!Object.values(MacAlgorithm).includes(macAlgorithm as MacAlgorithm)) {\n throw new CoseInvalidAlgorithmError('Invalid mac algorithm.')\n }\n\n this.structure.tag = await ctx.authenticate({\n toBeAuthenticated: Mac0.toBeAuthenticated({\n payload,\n protectedHeaders: this.protectedHeaders,\n externalAad: options.externalAad,\n }),\n algorithm: macAlgorithm,\n key: options.key,\n })\n return this\n }\n\n public async verifyAuthenticationCode(\n { key, detachedPayload, externalAad }: { key: CoseKey; detachedPayload?: Uint8Array; externalAad?: Uint8Array },\n ctx: Pick<Mac0Context, 'verify'>\n ) {\n const embeddedPayload = this.payload\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Mac0 already contains an embedded payload')\n }\n\n return await ctx.verify({\n key,\n tag: this.tag,\n toBeAuthenticated: this.toBeAuthenticated({ detachedPayload, externalAad }),\n algorithm: this.algorithm,\n })\n }\n}\n\naddExtension({\n Class: Mac0,\n tag: Mac0.tag,\n encode(instance: Mac0, encodeFn: (obj: unknown) => Uint8Array) {\n return encodeFn(instance)\n },\n decode: (encoded) => Mac0.fromEncodedStructure(encoded as Mac0EncodedStructure),\n})\n","import z from 'zod'\nimport {\n type AnyCborStructure,\n CborStructure,\n type CborStructureStaticThis,\n cborDecode,\n cborEncode,\n type EncodedStructureType,\n} from '../cbor'\nimport { addExtension } from '../cbor/cbor-x'\nimport { zUint8Array } from '../utils/zod'\nimport { CoseCertificateNotFoundError, CoseInvalidAlgorithmError, CosePayloadMustBeDefinedError } from './error'\nimport {\n type ProtectedHeaderOptions,\n ProtectedHeaders,\n protectedHeadersEncodedStructure,\n RegisteredCwtHeaderClaimKey,\n SignatureAlgorithm,\n type UnprotectedHeaderOptions,\n UnprotectedHeaders,\n unprotectedHeadersStructure,\n} from './headers'\nimport { type CoseKey, coseKeyToJwkClaim } from './key'\n\nexport const sign1EncodedSchema = z.tuple([\n // protected headers\n protectedHeadersEncodedStructure,\n // unprotected headers\n unprotectedHeadersStructure,\n // payload\n zUint8Array.nullable(),\n // signature\n zUint8Array,\n])\n\nexport const sign1DecodedSchema = z.object({\n protectedHeaders: z.instanceof(ProtectedHeaders),\n unprotectedHeaders: z.instanceof(UnprotectedHeaders),\n payload: sign1EncodedSchema.def.items[2],\n signature: sign1EncodedSchema.def.items[3],\n})\n\nexport type Sign1EncodedStructure = z.infer<typeof sign1EncodedSchema>\nexport type Sign1DecodedStructure = z.infer<typeof sign1DecodedSchema>\n\nexport type Sign1Context = {\n sign: (options: { toBeSigned: Uint8Array; key: CoseKey; algorithm: SignatureAlgorithm }) => Promise<Uint8Array>\n verify: (options: {\n toBeVerified: Uint8Array\n signature: Uint8Array\n key: CoseKey\n algorithm?: SignatureAlgorithm\n }) => Promise<boolean>\n}\n\nexport type Sign1Options = {\n protectedHeaders?: ProtectedHeaders | ProtectedHeaderOptions['protectedHeaders']\n unprotectedHeaders?: UnprotectedHeaders | UnprotectedHeaderOptions['unprotectedHeaders']\n\n /**\n * The embedded payload. Pass `null` to explicitly signal a detached payload\n * (the encoded structure will contain null, and you must supply the payload\n * via `detachedPayload` when calling `sign()` / `verifySignature()` / `toBeSigned()`).\n */\n payload: Uint8Array | null\n\n signature?: Uint8Array\n}\n\nexport class Sign1 extends CborStructure<Sign1EncodedStructure, Sign1DecodedStructure> {\n public static tag = 18\n protected override _tag = Sign1.tag\n\n public static override get encodingSchema() {\n return z.codec(sign1EncodedSchema, sign1DecodedSchema, {\n encode: (decoded) => {\n if (decoded.signature.length === 0) {\n throw new Error('Signature has not been set. Required for encoding the sign1 structure')\n }\n\n return [\n decoded.protectedHeaders.encodedStructure,\n decoded.unprotectedHeaders.encodedStructure,\n decoded.payload,\n decoded.signature,\n ] satisfies Sign1EncodedStructure\n },\n decode: ([protectedHeaders, unprotected, payload, signature]) => ({\n protectedHeaders: ProtectedHeaders.fromEncodedStructure(protectedHeaders),\n unprotectedHeaders: UnprotectedHeaders.fromEncodedStructure(unprotected),\n payload,\n signature,\n }),\n })\n }\n\n public get protectedHeaders() {\n return this.structure.protectedHeaders\n }\n\n public get unprotectedHeaders() {\n return this.structure.unprotectedHeaders\n }\n\n public get payload() {\n return this.structure.payload\n }\n\n public get signature() {\n return this.structure.signature\n }\n\n public get certificateChain() {\n return this.x5chain ?? []\n }\n\n public get certificate() {\n const [certificate] = this.certificateChain\n\n if (!certificate) {\n throw new CoseCertificateNotFoundError()\n }\n\n return certificate\n }\n\n /**\n * Returns the Sig_Structure bytes that are signed/verified.\n *\n * @param options.detachedPayload - The detached payload to use. Must be provided when\n * the Sign1 was created with a detached payload (i.e. `payload` field is null).\n * Cannot be provided when the Sign1 already contains an embedded payload.\n * @param options.externalAad - Externally supplied data covered by the signature. It is not part\n * of the COSE structure, so it has to be provided identically wherever the Sig_Structure is\n * built: `sign()`, `verifySignature()` and here.\n */\n public toBeSigned(options?: { detachedPayload?: Uint8Array; externalAad?: Uint8Array }): Uint8Array {\n const embeddedPayload = this.payload\n const detachedPayload = options?.detachedPayload\n\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Sign1 already contains an embedded payload')\n }\n\n const payload = embeddedPayload ?? detachedPayload\n\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n return Sign1.toBeSigned({\n payload,\n protectedHeaders: this.protectedHeaders,\n externalAad: options?.externalAad,\n })\n }\n\n /**\n * Decodes CBOR bytes into a Sign1 instance.\n * Uses the encodingSchema's decode() method to validate and transform the decoded data.\n */\n public static decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n const rawStructure = cborDecode(bytes)\n\n // May feel weird, but using new this makes TypeScript understand we may return a subclass\n return new this(\n // NOTE: If decoded with Sign1 tag, the cbor decoder already transforms to the class instances\n // In that case we create new instance based on the decoded structure, to ensure we create the\n // instance based on this (and ensure extended classes work)\n // biome-ignore lint/complexity/noThisInStatic: this check is intentional for subclass support\n rawStructure instanceof Sign1 && rawStructure.constructor === this\n ? rawStructure.decodedStructure\n : // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\n this.fromEncodedStructure(\n (rawStructure instanceof Sign1 ? rawStructure.encodedStructure : rawStructure) as EncodedStructureType<T>\n ).decodedStructure\n ) as unknown as T\n }\n\n public static toBeSigned(options: {\n payload: Uint8Array\n protectedHeaders: ProtectedHeaders\n externalAad?: Uint8Array\n }) {\n const toBeSigned = [\n 'Signature1',\n options.protectedHeaders.encodedStructure,\n options.externalAad ?? new Uint8Array(),\n options.payload,\n ]\n\n return cborEncode(toBeSigned)\n }\n\n public get algorithm(): SignatureAlgorithm | undefined {\n const algorithm = this.protectedHeaders.headers?.get(RegisteredCwtHeaderClaimKey.Algorithm) as\n | SignatureAlgorithm\n | undefined\n if (algorithm && !Object.values(SignatureAlgorithm).includes(algorithm)) {\n throw new CoseInvalidAlgorithmError()\n }\n\n return algorithm\n }\n\n public get jwaAlgorithm(): keyof typeof SignatureAlgorithm | undefined {\n const alg = this.algorithm\n if (!alg) return undefined\n\n const jwaAlg = coseKeyToJwkClaim.algorithm(alg)\n if (!jwaAlg) {\n throw new CoseInvalidAlgorithmError(`Cose algorithm ${alg} does not have a corresponding JWA alg`)\n }\n\n return jwaAlg\n }\n\n public get x5chain() {\n // TODO: typed keys for headers\n // FIXME: why are we looking at unprotected header for x5c?\n const x5chain =\n (this.protectedHeaders.headers?.get(RegisteredCwtHeaderClaimKey.X5Chain) as\n | Uint8Array\n | Uint8Array[]\n | undefined) ??\n (this.unprotectedHeaders.headers?.get(RegisteredCwtHeaderClaimKey.X5Chain) as\n | Uint8Array\n | Uint8Array[]\n | undefined)\n\n if (!x5chain?.[0]) {\n return undefined\n }\n\n return Array.isArray(x5chain) ? x5chain : [x5chain]\n }\n\n public async verifySignature(\n { key, detachedPayload, externalAad }: { key: CoseKey; detachedPayload?: Uint8Array; externalAad?: Uint8Array },\n ctx: Pick<Sign1Context, 'verify'>\n ) {\n const embeddedPayload = this.payload\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Sign1 already contains an embedded payload')\n }\n\n return await ctx.verify({\n toBeVerified: this.toBeSigned({ detachedPayload, externalAad }),\n signature: this.signature,\n key,\n algorithm: this.algorithm,\n })\n }\n\n public static create(options: Sign1Options) {\n const protectedHeaders =\n options.protectedHeaders instanceof ProtectedHeaders\n ? options.protectedHeaders\n : ProtectedHeaders.create({ protectedHeaders: options.protectedHeaders })\n\n const unprotectedHeaders =\n options.unprotectedHeaders instanceof UnprotectedHeaders\n ? options.unprotectedHeaders\n : UnprotectedHeaders.create({ unprotectedHeaders: options.unprotectedHeaders })\n\n const sign1 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n signature: options.signature ?? new Uint8Array(),\n })\n\n return sign1\n }\n\n public async sign(\n options: {\n externalAad?: Uint8Array\n signingKey: CoseKey\n algorithm?: SignatureAlgorithm\n detachedPayload?: Uint8Array\n },\n ctx: Pick<Sign1Context, 'sign'>\n ) {\n const embeddedPayload = this.payload\n const { detachedPayload } = options\n\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Sign1 already contains an embedded payload')\n }\n\n const payload = embeddedPayload ?? detachedPayload\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n const signatureAlgorithm = options.algorithm ?? options.signingKey.algorithm\n\n if (!signatureAlgorithm) {\n throw new CoseInvalidAlgorithmError(\n 'Could not establish signature algorithm. Either provide it in the options directly, or provide it in the signingKey'\n )\n }\n\n if (!Object.values(SignatureAlgorithm).includes(signatureAlgorithm as SignatureAlgorithm)) {\n throw new CoseInvalidAlgorithmError('algorithm provided in the options or key is not a valid signing algorithm')\n }\n\n this.structure.signature = await ctx.sign({\n toBeSigned: Sign1.toBeSigned({\n payload,\n protectedHeaders: this.protectedHeaders,\n externalAad: options.externalAad,\n }),\n key: options.signingKey,\n algorithm: signatureAlgorithm as SignatureAlgorithm,\n })\n\n return this\n }\n}\n\naddExtension({\n Class: Sign1,\n tag: Sign1.tag,\n encode(instance: Sign1, encodeFn: (obj: unknown) => Uint8Array) {\n return encodeFn(instance)\n },\n decode: (encoded) => Sign1.fromEncodedStructure(encoded as Sign1EncodedStructure),\n})\n","import type { AnyCborStructure, EncodedStructureType } from '../cbor'\nimport { cborDecode, describeCborValue } from '../cbor'\nimport { Tag } from '../cbor/cbor-x'\nimport type { AnyCwtPayload, CwtPayload } from './claims/cwt-payload'\nimport {\n CoseInvalidSignatureError,\n CosePayloadInvalidStructureError,\n CwtDetachedPayloadError,\n CwtMissingVerifyContextError,\n CwtNotSignedError,\n CwtPayloadDecodeError,\n} from './error'\nimport {\n type ProtectedHeaderOptions,\n ProtectedHeaders,\n RegisteredCwtHeaderClaimKey,\n type SignatureAlgorithm,\n type UnprotectedHeaderOptions,\n UnprotectedHeaders,\n} from './headers'\nimport type { CoseKey } from './key'\nimport { Mac0, type Mac0Context } from './mac0'\nimport { Sign1, type Sign1Context } from './sign1'\n\n/**\n * The CWT CBOR tag, defined in RFC 8392. It wraps the COSE structure rather than replacing it,\n * so a token tagged with it must be unwrapped before the COSE structure can be decoded.\n */\nconst CWT_TAG = 61\n\n/**\n * A raw header map is only accepted for a CWT that uses the default header structures. A CWT type\n * with its own header class has to be given an instance of that class, so that the map is validated\n * against the class's schema instead of the registered COSE header claims.\n */\ntype RawHeadersFor<Headers, Raw> = ProtectedHeaders extends Headers\n ? Raw\n : UnprotectedHeaders extends Headers\n ? Raw\n : never\n\nexport type CwtOptions<\n Payload extends AnyCwtPayload = CwtPayload,\n ProtectedHeadersStructure extends AnyProtectedHeaders = ProtectedHeaders,\n UnprotectedHeadersStructure extends AnyUnprotectedHeaders = UnprotectedHeaders,\n> = {\n protectedHeaders?:\n | ProtectedHeadersStructure\n | RawHeadersFor<ProtectedHeadersStructure, ProtectedHeaderOptions['protectedHeaders']>\n unprotectedHeaders?:\n | UnprotectedHeadersStructure\n | RawHeadersFor<UnprotectedHeadersStructure, UnprotectedHeaderOptions['unprotectedHeaders']>\n\n /** The CWT claims set. */\n payload: Payload\n\n /**\n * The COSE_Sign1 signature over the payload. Set for a signed CWT, and mutually exclusive with\n * {@link tag} — a CWT is one or the other.\n */\n signature?: Uint8Array\n\n /**\n * The COSE_Mac0 authentication tag over the payload. Set for a MACed CWT, and mutually exclusive\n * with {@link signature}.\n */\n tag?: Uint8Array\n\n /**\n * The payload bytes exactly as they appeared in the COSE message. Set when decoding a token, so\n * that verification can use them directly rather than re-encoding the decoded payload. Do not\n * pass this when constructing a CWT yourself.\n *\n * @see {@link Cwt.payloadBytes}\n */\n originalPayloadBytes?: Uint8Array\n}\n\n/**\n * The verification context {@link Cwt.verify} needs. Both are optional, so a caller that only deals\n * with one of the two COSE structures passes only that one, and a CWT carried in the other is\n * rejected rather than verified with the wrong context.\n */\nexport type CwtVerifyContext = {\n /** Verifies the signature of a CWT carried in a COSE_Sign1. */\n sign1?: Pick<Sign1Context, 'verify'>\n\n /** Verifies the authentication tag of a CWT carried in a COSE_Mac0. */\n mac0?: Pick<Mac0Context, 'verify'>\n}\n\n/**\n * The options the payload of `Cwt` takes for claim verification. Reading them off the payload class\n * is what lets a CWT type require its own options — a status list CWT its `uri`, say — on the `Cwt`\n * methods that forward to it.\n */\nexport type CwtClaimsOptionsFor<Payload extends AnyCwtPayload> = NonNullable<Parameters<Payload['verifyClaims']>[0]>\n\n/** The options {@link Cwt.verify} takes: the key, the claim options of its payload, and the AAD. */\nexport type CwtVerifyOptions<Payload extends AnyCwtPayload> = {\n key: CoseKey\n\n /**\n * Externally supplied data covered by the signature or authentication tag. It is not carried in\n * the token, so it has to be the same value the issuer signed with.\n */\n externalAad?: Uint8Array\n} & CwtClaimsOptionsFor<Payload>\n\n// biome-ignore lint/suspicious/noExplicitAny: intentionally unconstrained, used as a generic bound\nexport type AnyProtectedHeaders = ProtectedHeaders<any>\n// biome-ignore lint/suspicious/noExplicitAny: intentionally unconstrained, used as a generic bound\nexport type AnyUnprotectedHeaders = UnprotectedHeaders<any>\n\n// biome-ignore lint/suspicious/noExplicitAny: intentionally unconstrained, used as a generic bound\nexport type AnyCwt = Cwt<any, any, any>\n\n// biome-ignore lint/suspicious/noExplicitAny: matching any header structure\nexport type CwtPayloadType<T> = T extends Cwt<infer Payload, any, any> ? Payload : never\n// biome-ignore lint/suspicious/noExplicitAny: matching any payload/header structure\nexport type CwtProtectedHeadersType<T> = T extends Cwt<any, infer Headers, any> ? Headers : never\n// biome-ignore lint/suspicious/noExplicitAny: matching any payload/header structure\nexport type CwtUnprotectedHeadersType<T> = T extends Cwt<any, any, infer Headers> ? Headers : never\n\n/**\n * The static side of a `CborStructure` subclass, reduced to what decoding a CWT needs: turning an\n * encoded structure into a validated instance. Kept structural rather than `typeof SomeClass` so\n * that any subclass is accepted.\n */\nexport type CwtStructureClass<Structure extends AnyCborStructure> = {\n fromEncodedStructure(encodedStructure: EncodedStructureType<Structure>): Structure\n}\n\n/**\n * The structure classes a token is decoded into. Passed to {@link Cwt.fromToken}, which is the only\n * place that has to turn bytes back into structures, rather than declared as statics on the class:\n * a CWT type that wants to hide them overrides `fromToken` and supplies them there.\n */\nexport type CwtStructures<T extends AnyCwt> = {\n payload: CwtStructureClass<CwtPayloadType<T>>\n protectedHeaders?: CwtStructureClass<CwtProtectedHeadersType<T>>\n unprotectedHeaders?: CwtStructureClass<CwtUnprotectedHeadersType<T>>\n}\n\n/**\n * The static side of a `Cwt` subclass, so `fromToken` can construct (and type) the subclass it was\n * called on rather than the base class.\n */\nexport type CwtStaticThis<T extends AnyCwt> = {\n new (options: CwtOptions<CwtPayloadType<T>, CwtProtectedHeadersType<T>, CwtUnprotectedHeadersType<T>>): T\n}\n\n/**\n * A CBOR Web Token (RFC 8392): a COSE_Sign1 or COSE_Mac0 whose payload is a CWT claims set.\n *\n * A CWT type is expressed by the structures it is made of: a {@link CwtPayload} subclass for the\n * claims set, and a {@link ProtectedHeaders} / {@link UnprotectedHeaders} subclass for a header\n * bucket whose labels it adds to or narrows. Each of those validates itself through its own\n * `encodingSchema`, so `Cwt` holds no schemas and needs no per-type statics.\n *\n * The classes are named where a token is turned back into structures, which is `fromToken`:\n *\n * ```ts\n * const cwt = Cwt.fromToken(token, {\n * payload: StatusListCwtPayload,\n * protectedHeaders: StatusListCwtProtectedHeaders,\n * })\n *\n * cwt.payload.statusList // typed\n * ```\n *\n * A CWT type that carries extra logic subclasses `Cwt` and overrides `fromToken` to supply them, so\n * callers do not repeat the classes:\n *\n * ```ts\n * class StatusListCwt extends Cwt<StatusListCwtPayload, StatusListCwtProtectedHeaders> {\n * public static override fromToken(token: Uint8Array) {\n * return super.fromToken(token, {\n * payload: StatusListCwtPayload,\n * protectedHeaders: StatusListCwtProtectedHeaders,\n * })\n * }\n * }\n * ```\n *\n * @template Payload - The claims set structure for this CWT type.\n * @template ProtectedHeadersStructure - The protected header structure for this CWT type.\n * @template UnprotectedHeadersStructure - The unprotected header structure for this CWT type.\n */\nexport class Cwt<\n Payload extends AnyCwtPayload = CwtPayload,\n ProtectedHeadersStructure extends AnyProtectedHeaders = ProtectedHeaders,\n UnprotectedHeadersStructure extends AnyUnprotectedHeaders = UnprotectedHeaders,\n> {\n #payload: Payload\n\n /**\n * The claims set of this CWT.\n *\n * Assignable, and assigning drops the retained {@link originalPayloadBytes}, so the new claims set\n * is what gets signed or verified. Mutating the claims set in place cannot be seen from here, so\n * call {@link markPayloadModified} after doing so — the mutation helpers a CWT type exposes, such\n * as `StatusListCwt.updateStatusList`, already do.\n */\n public get payload(): Payload {\n return this.#payload\n }\n\n public set payload(payload: Payload) {\n this.#payload = payload\n this.markPayloadModified()\n }\n\n public protectedHeaders: ProtectedHeadersStructure\n public unprotectedHeaders: UnprotectedHeadersStructure\n\n /**\n * The COSE_Sign1 signature over the payload, for a signed CWT.\n *\n * Kept apart from {@link tag} rather than as one 'signature or tag' value, because which of the\n * two a CWT carries is what says whether it is a COSE_Sign1 or a COSE_Mac0 — a distinction the\n * encoded structure does not carry, and that {@link verify} needs.\n */\n public signature?: Uint8Array\n\n /** The COSE_Mac0 authentication tag over the payload, for a MACed CWT. See {@link signature}. */\n public tag?: Uint8Array\n\n /**\n * The payload bytes as received in the COSE message, kept so that verification can use them\n * directly. RFC 9052 puts the payload into `Sig_structure`/`MAC_structure` as an opaque `bstr`, so\n * what was signed is the exact bytes the issuer sent, not whatever we would encode the decoded\n * payload back into. Cleared by {@link markPayloadModified}, since the signature over it no longer\n * means anything once the payload changed.\n *\n * @see https://datatracker.ietf.org/doc/rfc9052/#section-4.4\n * @see https://datatracker.ietf.org/doc/rfc9052/#section-6\n */\n private originalPayloadBytes?: Uint8Array\n\n public constructor(options: CwtOptions<Payload, ProtectedHeadersStructure, UnprotectedHeadersStructure>) {\n // Set the field rather than going through the setter: there is nothing to invalidate yet, and\n // `originalPayloadBytes` is assigned below.\n this.#payload = options.payload\n\n // A raw map only reaches here for a CWT using the default header structures, see `RawHeadersFor`.\n // `create` validates it, so the headers of every CWT are checked by their own schema.\n this.protectedHeaders = (\n options.protectedHeaders instanceof ProtectedHeaders\n ? options.protectedHeaders\n : ProtectedHeaders.create({ protectedHeaders: options.protectedHeaders as Map<number, unknown> | undefined })\n ) as ProtectedHeadersStructure\n this.unprotectedHeaders = (\n options.unprotectedHeaders instanceof UnprotectedHeaders\n ? options.unprotectedHeaders\n : UnprotectedHeaders.create({\n unprotectedHeaders: options.unprotectedHeaders as Map<number, unknown> | undefined,\n })\n ) as UnprotectedHeadersStructure\n\n if (options.signature && options.tag) {\n throw new CosePayloadInvalidStructureError(\n 'A CWT carries either a COSE_Sign1 signature or a COSE_Mac0 authentication tag, not both'\n )\n }\n\n this.signature = options.signature\n this.tag = options.tag\n this.originalPayloadBytes = options.originalPayloadBytes\n }\n\n public static create<T extends AnyCwt>(\n this: CwtStaticThis<T>,\n options: CwtOptions<CwtPayloadType<T>, CwtProtectedHeadersType<T>, CwtUnprotectedHeadersType<T>>\n ): T {\n return new this(options)\n }\n\n /**\n * Decodes a CWT from a tagged COSE_Sign1 (tag 18) or COSE_Mac0 (tag 17) token.\n *\n * @throws CborDecodeError if the token is not valid CBOR.\n * @throws CosePayloadInvalidStructureError if the token is valid CBOR but not a COSE_Sign1/COSE_Mac0.\n * @throws CwtDetachedPayloadError if the token carries a detached (null) payload.\n * @throws CwtPayloadDecodeError if the payload is not a valid claims set for this CWT type. The\n * underlying error is available on the `cause` property.\n * @throws ZodValidationError if a header map is not valid for this CWT type's header structures.\n */\n public static fromToken<T extends AnyCwt>(\n this: CwtStaticThis<T>,\n token: Uint8Array,\n structures: CwtStructures<T>\n ): T {\n const coseStructure = Cwt.decodeCoseStructure(token)\n\n const payloadBytes = coseStructure.payload\n if (!payloadBytes) {\n throw new CwtDetachedPayloadError(\n 'Cwt does not contain a payload, a detached payload is not supported for a CWT as the claims set cannot be decoded'\n )\n }\n\n let payload: CwtPayloadType<T>\n try {\n payload = decodeStructure(structures.payload, cborDecode(payloadBytes))\n } catch (error) {\n throw new CwtPayloadDecodeError(\n `Unable to decode CWT payload: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n )\n }\n\n // The COSE structure only knows the base header classes, so the maps are re-read through this\n // CWT type's header structures, which is what validates them against its schema.\n const protectedHeaders = structures.protectedHeaders\n ? decodeStructure(\n structures.protectedHeaders,\n coseStructure.protectedHeaders.encodedStructure as EncodedStructureType<CwtProtectedHeadersType<T>>\n )\n : (coseStructure.protectedHeaders as CwtProtectedHeadersType<T>)\n const unprotectedHeaders = structures.unprotectedHeaders\n ? decodeStructure(\n structures.unprotectedHeaders,\n coseStructure.unprotectedHeaders.encodedStructure as EncodedStructureType<CwtUnprotectedHeadersType<T>>\n )\n : (coseStructure.unprotectedHeaders as CwtUnprotectedHeadersType<T>)\n\n return new this({\n payload,\n protectedHeaders,\n unprotectedHeaders,\n signature: coseStructure instanceof Sign1 ? coseStructure.signature : undefined,\n tag: coseStructure instanceof Mac0 ? coseStructure.tag : undefined,\n // Keep the exact bytes the issuer signed, see `originalPayloadBytes`.\n originalPayloadBytes: new Uint8Array(payloadBytes),\n })\n }\n\n /**\n * Decodes the COSE structure wrapping the CWT claims set.\n *\n * @throws CborDecodeError if the token is not valid CBOR.\n * @throws CosePayloadInvalidStructureError if the token is valid CBOR but not a COSE_Sign1/COSE_Mac0.\n */\n public static decodeCoseStructure(token: Uint8Array): Sign1 | Mac0 {\n const decoded = cborDecode<unknown>(token)\n\n // The tag 18/17 cbor-x extensions turn a COSE token into a Sign1/Mac0 instance. Anything\n // else decoded fine as CBOR but isn't a COSE token, and would otherwise be accepted here\n // and only surface much later as a confusing 'payload is missing' error.\n if (!(decoded instanceof Sign1) && !(decoded instanceof Mac0)) {\n const cwtTagHint =\n decoded instanceof Tag && decoded.tag === CWT_TAG ? ' (the CWT tag, which must be unwrapped first)' : ''\n\n throw new CosePayloadInvalidStructureError(\n `Expected a tagged COSE_Sign1 (tag ${Sign1.tag}) or COSE_Mac0 (tag ${Mac0.tag}) structure, but decoded ${describeCborValue(decoded)}${cwtTagHint}. ` +\n 'An untagged COSE structure is not supported; decode it with Sign1.decode or Mac0.decode instead.'\n )\n }\n\n return decoded\n }\n\n /**\n * The payload bytes that are signed or authenticated: the bytes as received when this CWT was\n * decoded from a token and the payload has not been modified since, and the re-encoded payload\n * otherwise.\n */\n public get payloadBytes(): Uint8Array {\n return this.originalPayloadBytes ?? this.payload.encode()\n }\n\n /**\n * Drops the retained {@link originalPayloadBytes}, so that the payload is re-encoded on the next\n * signing or verification. Call this after mutating {@link payload} in place, from a subclass or\n * from outside; assigning a new payload marks it automatically.\n */\n public markPayloadModified() {\n this.originalPayloadBytes = undefined\n }\n\n /**\n * `typ` (16), the media type of this CWT.\n *\n * Read from the protected headers only: RFC 9596 states that the `typ` parameter MUST NOT be\n * present in unprotected headers, so an unprotected one is not authoritative and reading it would\n * let anyone who can alter the token change what the token claims to be.\n *\n * @see https://www.rfc-editor.org/rfc/rfc9596.html#section-2\n */\n public get typ(): string | number | undefined {\n return this.protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.Typ)\n }\n\n /**\n * `alg` (1), the algorithm the CWT is signed or authenticated with.\n *\n * Read from the protected headers only. RFC 9052 requires `alg` to be authenticated, which for a\n * single recipient structure (COSE_Sign1 / COSE_Mac0) means the protected bucket or the externally\n * supplied data. An unprotected `alg` is attacker controlled, and is also not what\n * `Sign1.algorithm` / `Mac0.algorithm` pass to verification, so reading it here would report an\n * algorithm the signature was never checked against.\n *\n * @see https://www.rfc-editor.org/rfc/rfc9052.html#section-3.1\n */\n public get algorithm(): string | number | undefined {\n return this.protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.Algorithm)\n }\n\n /**\n * `kid` (4), a hint for which key to verify with.\n *\n * Read from the protected headers, falling back to the unprotected ones: RFC 9052 calls `kid` a\n * hint that \"is not a security-critical field\" and explicitly allows it in the unprotected bucket,\n * where it is commonly placed.\n *\n * @see https://www.rfc-editor.org/rfc/rfc9052.html#section-3.1\n */\n public get keyId(): Uint8Array | undefined {\n return (\n this.protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.KeyId) ??\n this.unprotectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.KeyId)\n )\n }\n\n /** The proof this CWT carries, whichever of the two it is: its {@link signature} or its {@link tag}. */\n public get signatureOrTag(): Uint8Array | undefined {\n return this.signature ?? this.tag\n }\n\n public get asSign1() {\n return Sign1.create({\n protectedHeaders: this.protectedHeaders,\n unprotectedHeaders: this.unprotectedHeaders,\n payload: this.payloadBytes,\n signature: this.signature,\n })\n }\n\n public get asMac0() {\n return Mac0.create({\n protectedHeaders: this.protectedHeaders,\n unprotectedHeaders: this.unprotectedHeaders,\n payload: this.payloadBytes,\n tag: this.tag,\n })\n }\n\n public async signAndEncode(\n options: { signingKey: CoseKey; algorithm?: SignatureAlgorithm; externalAad?: Uint8Array },\n ctx: Pick<Sign1Context, 'sign'>\n ) {\n return (await this.asSign1.sign(options, ctx)).encode()\n }\n\n public async authenticateAndEncode(\n options: { key: CoseKey; externalAad?: Uint8Array },\n ctx: Pick<Mac0Context, 'authenticate'>\n ) {\n return (await this.asMac0.authenticate(options, ctx)).encode()\n }\n\n /**\n * Verifies the claims of this CWT's payload. See `CwtPayload.verifyClaims` for what is checked; a\n * CWT type that narrows its payload class narrows this along with it, options included.\n *\n * This checks the claims only. {@link verify} checks the signature or authentication tag as well,\n * and is what a verifier wants: the claims of a token whose issuer has not been established mean\n * nothing.\n *\n * @throws CwtClaimVerificationError if a required claim is missing, a claim does not match what\n * was expected, or the token is outside its validity window.\n */\n public verifyClaims(options: CwtClaimsOptionsFor<Payload>): void {\n this.payload.verifyClaims(options)\n }\n\n /**\n * Verifies this CWT completely: the signature or authentication tag over the payload, and then\n * the claims in it.\n *\n * Which of the two is checked follows whether this CWT carries a {@link signature} or a\n * {@link tag}, and the matching entry of `ctx` is used, so a caller does not have to know which\n * of the two structures a token turned out to be.\n *\n * @throws CwtNotSignedError if the CWT carries neither, and so has nothing to verify.\n * @throws CwtMissingVerifyContextError if `ctx` has no entry for the structure this CWT is.\n * @throws CoseInvalidSignatureError if the signature or authentication tag does not verify.\n * @throws CwtClaimVerificationError if the claims do not, see {@link verifyClaims}.\n */\n public async verify(\n { key, externalAad, ...claimsOptions }: CwtVerifyOptions<Payload>,\n ctx: CwtVerifyContext\n ): Promise<void> {\n if (this.tag !== undefined) {\n if (!ctx.mac0) {\n throw new CwtMissingVerifyContextError(\n 'The CWT carries a COSE_Mac0 authentication tag, but no `mac0` verification context was provided'\n )\n }\n\n if (!(await this.verifyAuthenticationCode({ key, externalAad }, ctx.mac0))) {\n throw new CoseInvalidSignatureError(\n 'The authentication tag of the CWT could not be verified with the provided key'\n )\n }\n } else if (this.signature !== undefined) {\n if (!ctx.sign1) {\n throw new CwtMissingVerifyContextError(\n 'The CWT carries a COSE_Sign1 signature, but no `sign1` verification context was provided'\n )\n }\n\n if (!(await this.verifySignature({ key, externalAad }, ctx.sign1))) {\n throw new CoseInvalidSignatureError('The signature of the CWT could not be verified with the provided key')\n }\n } else {\n throw new CwtNotSignedError(\n 'The CWT carries neither a signature nor an authentication tag, so there is nothing to verify. ' +\n 'Decode a signed or authenticated token with `fromToken` to verify it.'\n )\n }\n\n // NOTE: cast because TypeScript cannot see that the rest of a generic intersection is still the\n // payload's options type.\n this.verifyClaims(claimsOptions as CwtClaimsOptionsFor<Payload>)\n }\n\n public async verifySignature(options: { key: CoseKey; externalAad?: Uint8Array }, ctx: Pick<Sign1Context, 'verify'>) {\n return await this.asSign1.verifySignature(options, ctx)\n }\n\n public async verifyAuthenticationCode(\n options: { key: CoseKey; externalAad?: Uint8Array },\n ctx: Pick<Mac0Context, 'verify'>\n ) {\n return await this.asMac0.verifyAuthenticationCode(options, ctx)\n }\n}\n\n/**\n * Builds a structure instance from its encoded form, validating it against the class's own\n * `encodingSchema`. Mirrors `CborStructure.decode`, but for a class passed in as a value rather than\n * called as a static, which is how a CWT names the structures it is made of.\n */\nfunction decodeStructure<Structure extends AnyCborStructure>(\n structureClass: CwtStructureClass<Structure>,\n encodedStructure: EncodedStructureType<Structure>\n): Structure {\n // NOTE: the instance `fromEncodedStructure` builds is used as is, rather than re-wrapped around\n // its decoded structure: a structure can carry more than that map — `ProtectedHeaders` keeps the\n // bstr it was decoded from — and re-wrapping would drop it.\n return structureClass.fromEncodedStructure(encodedStructure)\n}\n"],"mappings":";;;;;;AAGA,EAAE,OAAO,EACP,aAAa,eAAe,EAC9B,CAAC;AAED,SAAS,eAAe,OAA4B;CAClD,IAAI,CAAC,OAAO,OAAO;CAEnB,OAAO,UAAU,OAAO;EACtB,QAAQ;EACR,iBAAiB;EACjB,gBAAgB;EAChB,gBAAgB;CAClB,CAAC,CAAC,CAAC,SAAS;AACd;AAIA,IAAa,kBAAb,cAAqC,MAAM;CAGzC,YAAY,SAAiB,UAAqB;EAChD,MAAM,OAAO;EAEb,MAAM,iBAAiB,WAAW,eAAe,QA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AAK,aAAa,GAAG,iBACvB,KACe;EACf,IAAI,KAAK,QAAQ,KAAA,GAAW;GAC1B,IAAI,CAAC,IAAI,MACP,MAAM,IAAI,6BACR,iGACF;GAGF,IAAI,CAAE,MAAM,KAAK,yBAAyB;IAAE;IAAK;GAAY,GAAG,IAAI,IAAI,GACtE,MAAM,IAAI,0BACR,+EACF;EAEJ,OAAO,IAAI,KAAK,cAAc,KAAA,GAAW;GACvC,IAAI,CAAC,IAAI,OACP,MAAM,IAAI,6BACR,0FACF;GAGF,IAAI,CAAE,MAAM,KAAK,gBAAgB;IAAE;IAAK;GAAY,GAAG,IAAI,KAAK,GAC9D,MAAM,IAAI,0BAA0B,sEAAsE;EAE9G,OACE,MAAM,IAAI,kBACR,qKAEF;EAKF,KAAK,aAAa,aAA6C;CACjE;CAEA,MAAa,gBAAgB,SAAqD,KAAmC;EACnH,OAAO,MAAM,KAAK,QAAQ,gBAAgB,SAAS,GAAG;CACxD;CAEA,MAAa,yBACX,SACA,KACA;EACA,OAAO,MAAM,KAAK,OAAO,yBAAyB,SAAS,GAAG;CAChE;AACF;;;;;;AAOA,SAAS,gBACP,gBACA,kBACW;CAIX,OAAO,eAAe,qBAAqB,gBAAgB;AAC7D"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["z","z","z","z"],"sources":["../src/utils/zod-error.ts","../src/utils/zod.ts","../src/cbor/cbor-x.ts","../src/cbor/error.ts","../src/cbor/parser.ts","../src/cbor/data-item.ts","../src/cbor/cbor-structure.ts","../src/cbor/describe.ts","../src/cbor/models/date.ts","../src/cbor/models/date-only.ts","../src/utils/typed-map.ts","../src/cose/error.ts","../src/cose/claims/default.ts","../src/cose/claims/cwt-payload.ts","../src/cose/headers/defaults.ts","../src/cose/headers/header-claims.ts","../src/cose/headers/protected-headers.ts","../src/cose/headers/unprotected-headers.ts","../src/cose/headers/x5chain.ts","../src/cose/key/curve.ts","../src/cose/key/key-operation.ts","../src/cose/key/key-type.ts","../src/cose/key/jwk.ts","../src/cose/key/key.ts","../src/cose/mac0.ts","../src/cose/sign1.ts","../src/cose/cwt.ts"],"sourcesContent":["import z from 'zod'\nimport { createErrorMap, fromError } from 'zod-validation-error'\n\nz.config({\n customError: createErrorMap(),\n})\n\nfunction formatZodError(error?: z.ZodError): string {\n if (!error) return ''\n\n return fromError(error, {\n prefix: '',\n prefixSeparator: '✖ ',\n issueSeparator: '\\n✖ ',\n unionSeparator: '\\n OR ✖ ',\n }).toString()\n}\n\nimport type { ZodError } from 'zod'\n\nexport class ValidationError extends Error {\n public zodError: ZodError | undefined\n\n constructor(message: string, zodError?: ZodError) {\n super(message)\n\n const formattedError = zodError ? formatZodError(zodError) : ''\n this.message = `${message}\\n${formattedError}`\n\n Object.defineProperty(this, 'zodError', {\n value: zodError,\n writable: false,\n enumerable: false,\n })\n }\n}\n","import z from 'zod'\nimport type { $ZodType } from 'zod/v4/core'\nimport { ValidationError } from './zod-error'\n\nexport const zUint8Array = z.instanceof<typeof Uint8Array<ArrayBufferLike>>(Uint8Array)\n\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\ntype ZodTypeAny = $ZodType<any, any, any>\n\nexport function parseStructureWithErrorHandling<Schema extends ZodTypeAny>(\n structureName: string,\n schema: Schema,\n data: unknown,\n customErrorMessage?: string\n): z.infer<Schema> {\n const parseResult = z.safeParse(schema, data)\n\n if (!parseResult.success) {\n throw new ValidationError(customErrorMessage ?? `Error decoding ${structureName}`, parseResult.error)\n }\n\n return parseResult.data\n}\n\nexport function decodeStructureWithErrorHandling<Schema extends ZodTypeAny>(\n structureName: string,\n schema: Schema,\n data: z.input<Schema>,\n customErrorMessage?: string\n): z.infer<Schema> {\n const decodeResult = z.safeDecode(schema, data)\n\n if (!decodeResult.success) {\n throw new ValidationError(customErrorMessage ?? `Error decoding ${structureName}`, decodeResult.error)\n }\n\n return decodeResult.data\n}\n\nexport function encodeStructureWithErrorHandling<Schema extends ZodTypeAny>(\n structureName: string,\n schema: Schema,\n data: z.output<Schema>,\n customErrorMessage?: string\n): z.input<Schema> {\n const encodeResult = z.safeEncode(schema, data)\n\n if (!encodeResult.success) {\n throw new ValidationError(customErrorMessage ?? `Error encoding ${structureName}`, encodeResult.error)\n }\n\n return encodeResult.data\n}\n","import type { Tag as CborXTag } from 'cbor-x'\nimport * as cborXDecode from 'cbor-x/decode'\n\nexport type { Options } from 'cbor-x'\nexport { addExtension, Encoder } from 'cbor-x/encode'\n\nexport const Tag = (cborXDecode as unknown as { Tag: typeof CborXTag }).Tag\nexport type Tag = CborXTag\n","// biome-ignore format: no explanation\nclass CborError extends Error {\n // NOTE: declared explicitly rather than passing `{ cause }` to `super`, as the\n // project targets ES2020 and `Error.cause` was only added in ES2022.\n public readonly cause?: unknown\n\n constructor(message: string = new.target.name, options?: { cause?: unknown }) {\n super(message)\n this.name = new.target.name\n this.cause = options?.cause\n }\n}\n\nexport class CborDecodeError extends CborError {}\nexport class CborEncodeError extends CborError {}\n","import { Encoder, type Options } from './cbor-x'\nimport { DataItem } from './data-item'\nimport { CborDecodeError, CborEncodeError } from './error'\n\nexport type CborOptions = Options & {\n unwrapTopLevelDataItem?: boolean\n}\n\nconst encoderDefaults: CborOptions = {\n tagUint8Array: false,\n useRecords: false,\n mapsAsObjects: false,\n unwrapTopLevelDataItem: true,\n variableMapSize: true,\n}\n\nexport const cborDecode = <T>(input: Uint8Array, options: CborOptions = encoderDefaults): T => {\n const params = { ...encoderDefaults, ...options }\n const enc = new Encoder(params)\n\n let decoded: unknown\n try {\n decoded = enc.decode(input)\n } catch (error) {\n // cbor-x errors ('Data read, but end of buffer not reached', 'Unexpected end of CBOR data',\n // ...) give no indication of what was being decoded. Wrap them so callers can tell a\n // malformed input apart from a structurally valid one that failed validation later on.\n throw new CborDecodeError(\n `Unable to decode ${input.length} bytes as CBOR: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n )\n }\n\n return params.unwrapTopLevelDataItem && typeof decoded === 'object' && decoded instanceof DataItem\n ? (decoded.data as T)\n : (decoded as T)\n}\n\nexport const cborEncode = (obj: unknown, options: Options = encoderDefaults): Uint8Array => {\n const params = { ...encoderDefaults, ...options }\n const enc = new Encoder(params)\n\n try {\n return Uint8Array.from(enc.encode(obj))\n } catch (error) {\n throw new CborEncodeError(\n `Unable to encode value as CBOR: ${error instanceof Error ? error.message : String(error)}`,\n {\n cause: error,\n }\n )\n }\n}\n","import z from 'zod'\nimport { addExtension } from './cbor-x'\nimport { cborDecode, cborEncode } from './parser'\n\nexport const zDataItemCodec = (outputSchema: z.ZodType) =>\n z.codec(z.instanceof(DataItem), outputSchema, {\n encode: (data) => DataItem.fromData(data),\n decode: (dataItem) => dataItem.data,\n })\n\nexport type DataItemOptions<T = unknown> =\n | {\n data: T\n buffer: Uint8Array\n }\n | { data: T }\n | { buffer: Uint8Array }\n\n/**\n * DataItem is an extension defined https://www.rfc-editor.org/rfc/rfc8949.html#name-encoded-cbor-data-item\n * > Sometimes it is beneficial to carry an embedded CBOR data item that is\n * > not meant to be decoded immediately at the time the enclosing data item is being decoded.\n *\n * The idea of this class is to provide lazy encode and decode of cbor data.\n *\n * Due to a bug in the cbor-x library, we are eagerly encoding the data in the constructor.\n * https://github.com/kriszyp/cbor-x/issues/83\n *\n */\nexport class DataItem<T = unknown> {\n #data?: T\n #buffer: Uint8Array\n\n public constructor(options: DataItemOptions<T>) {\n if (!('data' in options) && !('buffer' in options)) {\n throw new Error('DataItem must be initialized with either the data or a buffer')\n }\n\n if ('data' in options) this.#data = options.data\n this.#buffer = 'buffer' in options ? options.buffer : cborEncode(options.data)\n }\n\n public get data(): T {\n if (!this.#data) {\n this.#data = cborDecode(this.#buffer) as T\n }\n return this.#data\n }\n\n public get buffer(): Uint8Array {\n return this.#buffer\n }\n\n public static fromData<T>(data: T): DataItem<T> {\n return new DataItem({ data })\n }\n\n public static fromBuffer<T>(buffer: Uint8Array): DataItem<T> {\n return new DataItem({ buffer })\n }\n}\n\naddExtension({\n Class: DataItem,\n tag: 24,\n encode: (instance: DataItem<unknown>, encode) => {\n return encode(instance.buffer)\n },\n decode: (buffer: Uint8Array): object => {\n return DataItem.fromBuffer(buffer)\n },\n})\n","// biome-ignore-all lint: @biomejs/biome seems to change the `new this(...)` calls into `new CborStructure(...)` which seems to cause a bug for this specific use case. We cannot alias to `thiz` or disable a specific rule\n\nimport { z } from 'zod'\nimport {\n decodeStructureWithErrorHandling,\n encodeStructureWithErrorHandling,\n parseStructureWithErrorHandling,\n} from '../utils/zod'\nimport { Tag } from './cbor-x'\nimport { DataItem } from './data-item'\nimport { cborDecode, cborEncode } from './parser'\n\nexport type CborEncodeOptions = {\n asDataItem?: boolean\n}\n\nexport type AnyCborStructure = CborStructure<any, any>\nexport type EncodedStructureType<T> = T extends CborStructure<infer EncodedStructure, unknown> ? EncodedStructure : any\nexport type DecodedStructureType<T> = T extends CborStructure<unknown, infer DecodedStructure> ? DecodedStructure : any\n\nexport type CborStructureStaticThis<T extends AnyCborStructure> = {\n new (structure: any): T\n encodingSchema: z.ZodType<any, any, any> | undefined\n fromEncodedStructure: (encodedStructure: EncodedStructureType<T>) => { decodedStructure: DecodedStructureType<T> }\n}\n\nexport class CborStructure<EncodedStructure = unknown, DecodedStructure = EncodedStructure> {\n protected structure: DecodedStructure\n protected _tag: number | undefined\n\n public constructor(structure: DecodedStructure) {\n this.structure = structure\n }\n\n public get decodedStructure(): DecodedStructure {\n return this.structure\n }\n\n /**\n * Static getter for the Zod codec schema that defines the CBOR structure.\n * Subclasses CAN override this to provide their specific schema for automatic encoding/decoding.\n * The schema should be a Zod schema or codec that handles validation and transformation.\n * If not provided, subclasses must override encode(), decode(), and fromEncodedStructure().\n */\n public static get encodingSchema(): z.ZodType | undefined {\n return undefined\n }\n\n /**\n * Returns the encoded structure that will be serialized to CBOR.\n * By default, returns the protected structure property.\n * Override if custom encoding logic is needed.\n */\n public get encodedStructure(): EncodedStructure {\n const encodingSchema = (this.constructor as typeof CborStructure).encodingSchema\n if (!encodingSchema) {\n throw new Error('encodedStructure must be implemented when encodingSchema is not provided')\n }\n\n return encodeStructureWithErrorHandling(this.constructor.name, encodingSchema, this.structure) as EncodedStructure\n }\n\n /**\n * Encodes this structure to CBOR bytes.\n */\n public encode(options?: CborEncodeOptions): Uint8Array {\n const encodedStructure = options?.asDataItem ? DataItem.fromData(this.encodedStructure) : this.encodedStructure\n const tagged = this._tag ? new Tag(encodedStructure, this._tag) : encodedStructure\n\n return cborEncode(tagged)\n }\n\n /**\n * Decodes CBOR bytes into a structure instance.\n * Uses the encodingSchema's decode() method to validate and transform the decoded data.\n */\n public static decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n const rawStructure = cborDecode(bytes)\n\n // May feel weird, but using new this makes TypeScript understand we may return a subclass\n return new this(this.fromEncodedStructure(rawStructure as EncodedStructureType<T>).decodedStructure)\n }\n\n /**\n * Creates a structure instance from the encoded CBOR structure (after calling cborDecode).\n *\n * Uses the encodingSchema's decode() method to validate and transform the structure if available.\n * Otherwise, subclasses must override this method.\n */\n public static fromEncodedStructure<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n encodedStructure: EncodedStructureType<T>\n ): T {\n if (!this.encodingSchema) {\n throw new Error('fromEncodedStructure must be implemented when encodingSchema is not provided')\n }\n\n return new this(decodeStructureWithErrorHandling(this.name, this.encodingSchema, encodedStructure))\n }\n\n public static fromDataItem<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, dataItem: unknown): T {\n return new this(\n parseStructureWithErrorHandling(\n this.name,\n z\n .instanceof(DataItem)\n .transform((di) => di.data)\n .transform((d) => this.fromEncodedStructure(d as any).decodedStructure),\n dataItem,\n `Error decoding ${this.name} from DateItem`\n )\n )\n }\n\n /**\n * Creates a structure instance from the decoded structure.\n *\n * Uses the encodingSchema's parse method to validate the structure if available.\n * Otherwise, subclasses must override this method.\n */\n public static fromDecodedStructure<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n decodedStructure: DecodedStructureType<T>\n ): T {\n const encodingSchema = this.encodingSchema\n if (!encodingSchema) {\n throw new Error('fromDecodedStructure must be implemented when encodingSchema is not provided')\n }\n\n // When the schema is a codec, we need to validate it against the output schema, not the input schema\n const decodedSchema = encodingSchema instanceof z.ZodPipe ? encodingSchema.out : encodingSchema\n\n return new this(parseStructureWithErrorHandling(this.name, decodedSchema, decodedStructure))\n }\n}\n","import { Tag } from './cbor-x'\nimport { DataItem } from './data-item'\n\nconst MAX_DESCRIBED_STRING_LENGTH = 40\n\n/**\n * Describes a decoded CBOR value in a form suitable for error messages, so a caller can tell\n * what their input actually was instead of only learning what it wasn't.\n *\n * Only describes the shape of the top-level value; it does not recurse into containers.\n */\nexport function describeCborValue(value: unknown): string {\n if (value === null) return 'null'\n if (value === undefined) return 'undefined'\n\n if (value instanceof Tag) return `a CBOR value tagged with tag ${value.tag}`\n if (value instanceof DataItem) return 'an encoded CBOR data item (tag 24)'\n\n if (Array.isArray(value)) {\n return `an untagged array with ${value.length} ${value.length === 1 ? 'element' : 'elements'}`\n }\n if (value instanceof Map) return `an untagged map with ${value.size} ${value.size === 1 ? 'entry' : 'entries'}`\n if (value instanceof Uint8Array) return `a byte string of ${value.length} bytes`\n\n if (typeof value === 'string') {\n const truncated =\n value.length > MAX_DESCRIBED_STRING_LENGTH ? `${value.slice(0, MAX_DESCRIBED_STRING_LENGTH)}…` : value\n return `the text string '${truncated}'`\n }\n\n if (typeof value === 'object') return `a value of type ${value.constructor?.name ?? 'object'}`\n\n return `the ${typeof value} value '${String(value)}'`\n}\n","import { addExtension } from '../cbor-x'\n\n// tdate data item shall contain a date-time string as specified in RFC 3339 (with no fraction of seconds)\n// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6\naddExtension({\n Class: Date,\n tag: 0,\n encode: (date: Date, encode) => encode(`${date.toISOString().split('.')[0]}Z`),\n decode: (isoStringDateTime: string) => new Date(isoStringDateTime),\n})\n","import { addExtension } from '../cbor-x'\n\nconst customInspectSymbol = Symbol.for('nodejs.util.inspect.custom')\nexport class DateOnly {\n private date: Date\n\n public constructor(date?: string) {\n this.date = date ? new Date(date) : new Date()\n }\n\n get [Symbol.toStringTag]() {\n return DateOnly.name\n }\n\n toString() {\n return this.toISOString()\n }\n\n toJSON() {\n return this.toISOString()\n }\n\n toISOString(): string {\n return this.date.toISOString().split('T')[0]\n }\n\n [customInspectSymbol](): string {\n return this.toISOString()\n }\n}\n\n// full-date data item shall contain a full-date string as specified in RFC 3339\n// see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6\naddExtension({\n Class: DateOnly,\n tag: 1004,\n encode: (date: DateOnly, encode) => encode(date.toISOString()),\n decode: (isoStringDate: string) => new DateOnly(isoStringDate),\n})\n","import { z } from 'zod'\nimport type zCore from 'zod/v4/core'\n\n/**\n * TypedMap provides compile-time type safety for Maps where each key has its own specific value type.\n * Unlike Map<K, V> which has the same value type V for all keys, TypedMap<Schema, OptionalKeys>\n * allows different value types per key (heterogeneous values).\n *\n * Example:\n * type CoseKeySchema = {\n * [CoseKeyParameter.KeyType]: KeyType // number key → KeyType value\n * [CoseKeyParameter.Curve]: Curve // number key → Curve value\n * [CoseKeyParameter.X]: Uint8Array // number key → Uint8Array value\n * }\n *\n * const map = new TypedMap<CoseKeySchema>()\n * map.get(CoseKeyParameter.KeyType) // TypeScript knows this is KeyType!\n * map.get(CoseKeyParameter.Curve) // TypeScript knows this is Curve!\n * map.get(CoseKeyParameter.X) // TypeScript knows this is Uint8Array!\n *\n * @template Schema - Object type mapping keys to their value types\n * @template OptionalKeys - Union of keys that are optional (can be absent)\n */\n\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\nexport class TypedMap<Schema extends Record<PropertyKey, any>, OptionalKeys extends keyof Schema = never> {\n private readonly map: Map<keyof Schema, Schema[keyof Schema]>\n\n /**\n * Called whenever an entry is added, changed or removed. Set by a structure that caches the bytes\n * it was decoded from, so that the cache is dropped as soon as the map no longer matches them.\n *\n * NOTE: only changes made through this map are seen. Mutating a value in place —\n * `map.get(key)[0] = 1` — does not go through `set`/`delete`/`clear` and does not fire this, so a\n * structure that caches its encoded form has to be told about such a change explicitly.\n */\n public onChange?: () => void\n\n constructor(entries?: (readonly [keyof Schema, Schema[keyof Schema]])[] | null) {\n this.map = new Map(entries)\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n public static fromMap<Schema extends Record<PropertyKey, any>, OptionalKeys extends keyof Schema = never>(\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n map: Map<any, any>\n ) {\n return new TypedMap<Schema, OptionalKeys>(Array.from(map.entries()))\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n public static fromObject<Schema extends Record<PropertyKey, any>, OptionalKeys extends keyof Schema = never>(\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n object: Record<string | number, any>\n ) {\n return new TypedMap<Schema, OptionalKeys>(Array.from(Object.entries(object)))\n }\n\n /**\n * Type-safe get that returns the correct value type for each key.\n * Required keys return T, optional keys return T | undefined.\n */\n get<K extends keyof Schema>(key: K): K extends OptionalKeys ? Schema[K] | undefined : Schema[K] {\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n return this.map.get(key) as any\n }\n\n /**\n * Type-safe set that ensures the value matches the key's type\n */\n set<K extends keyof Schema>(key: K, value: Schema[K]): this {\n this.map.set(key, value)\n this.onChange?.()\n return this\n }\n\n has(key: keyof Schema): boolean {\n return this.map.has(key)\n }\n\n delete(key: keyof Schema): boolean {\n const deleted = this.map.delete(key)\n if (deleted) this.onChange?.()\n return deleted\n }\n\n clear(): void {\n if (this.map.size === 0) return\n this.map.clear()\n this.onChange?.()\n }\n\n get size(): number {\n return this.map.size\n }\n\n keys(): IterableIterator<keyof Schema> {\n return this.map.keys()\n }\n\n values(): IterableIterator<Schema[keyof Schema]> {\n return this.map.values()\n }\n\n entries(): IterableIterator<[keyof Schema, Schema[keyof Schema]]> {\n return this.map.entries()\n }\n\n forEach(\n callbackfn: (value: Schema[keyof Schema], key: keyof Schema, map: Map<keyof Schema, Schema[keyof Schema]>) => void,\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n thisArg?: any\n ): void {\n this.map.forEach(callbackfn, thisArg)\n }\n\n [Symbol.iterator](): IterableIterator<[keyof Schema, Schema[keyof Schema]]> {\n return this.map[Symbol.iterator]()\n }\n\n toMap(): Map<keyof Schema, Schema[keyof Schema]> {\n return new Map(this.map)\n }\n}\n\n// Helper type to build schema from entries array\n// biome-ignore lint/suspicious/noExplicitAny: no explanation\ntype EntriesArrayToSchema<T extends ReadonlyArray<readonly [any, any]>> = {\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n [K in T[number][0]]: Extract<T[number], readonly [K, any]>[1]\n}\n\n/**\n * This checks whether the property is exact optional. exact optional means that the value cannot be undefined, but if used\n * in an object the key can be omitted. This is important for CBOR structures, as undefined will be encoded, and thus must be\n * omitted in most cases.\n *\n * Zod recommend to check for optionality by just parsing undefined.\n */\nconst isExactOptional = (schema: z.ZodType) =>\n !schema.safeParse(undefined).success && z.object({ test: schema }).safeParse({}).success\n\n/**\n * Names a map key for an error message: `ExpirationTime (4)` when `keyLabels` has a name for the\n * key, and the bare label otherwise.\n *\n * `RegisteredCwtClaimKey[4]` is `'ExpirationTime'` for a numeric enum, so a reverse-mapped string\n * is a name. A numeric value is the enum's forward mapping and not a name.\n *\n * @see the `keyLabels` option of {@link typedMap}\n */\nexport function keyLabel(key: string | number, keyLabels?: Record<string | number, unknown>): string {\n const label = keyLabels?.[key]\n return typeof label === 'string' ? `${label} (${key})` : `${key}`\n}\n\nexport type EntriesBase = ReadonlyArray<\n readonly [\n string | number, // for now we only allow string or number keys\n // biome-ignore lint/suspicious/noExplicitAny: no explanation\n z.ZodType<any>,\n ]\n>\n\n/**\n * A `TypedMap` with any schema. Useful as a generic constraint for structures that are generic over\n * the shape of their map, where the concrete schema is supplied by a subclass.\n */\n// biome-ignore lint/suspicious/noExplicitAny: intentionally unconstrained, used as a generic bound\nexport type AnyTypedMap = TypedMap<any, any>\n\ntype EntryKey<Entry> = Entry extends readonly [infer Key, z.ZodType] ? Key : never\n\n/**\n * Drops every entry from `Entries` whose key is present in `Keys`, preserving tuple order.\n */\ntype WithoutEntryKeys<Entries extends EntriesBase, Keys> = Entries extends readonly [\n infer Head,\n ...infer Rest extends EntriesBase,\n]\n ? EntryKey<Head> extends Keys\n ? WithoutEntryKeys<Rest, Keys>\n : readonly [Head, ...WithoutEntryKeys<Rest, Keys>]\n : readonly []\n\nexport type ExtendedEntries<Base extends EntriesBase, Extra extends EntriesBase> = readonly [\n ...WithoutEntryKeys<Base, Extra[number][0]>,\n ...Extra,\n]\n\n/**\n * Merges a base set of `typedMap` entries with additional ones, so a structure can be extended for a\n * specific profile (e.g. a status list CWT payload extending the registered CWT claims).\n *\n * An entry in `extra` that reuses a key from `base` replaces it, both in the resulting type and at\n * runtime. That is what makes it possible to narrow an inherited claim, e.g. turning the optional\n * registered `sub` claim into a required one. Without the replacement the two schemas for the same\n * key would collapse into a union and the key would stay optional.\n */\nexport function extendTypedMapEntries<const Base extends EntriesBase, const Extra extends EntriesBase>(\n base: Base,\n extra: Extra\n): ExtendedEntries<Base, Extra> {\n const overriddenKeys = new Set<string | number>(extra.map(([key]) => key))\n\n return [...base.filter(([key]) => !overriddenKeys.has(key)), ...extra] as unknown as ExtendedEntries<Base, Extra>\n}\n\ntype InferredEntries<Entries extends EntriesBase> = {\n [K in keyof Entries]: readonly [Entries[K][0], z.infer<Entries[K][1]>]\n}\ntype InferredSchema<Entries extends EntriesBase> = EntriesArrayToSchema<InferredEntries<Entries>>\n\ntype OptionalKeys<Entries extends EntriesBase> = Entries[number] extends infer E\n ? E extends readonly [infer K, infer V]\n ? // biome-ignore lint/suspicious/noExplicitAny: no explanation\n V extends z.ZodExactOptional<any>\n ? K\n : never\n : never\n : never\n\n/**\n * Utility function to create a typed map codec.\n * Takes an array of [key, valueSchema] entries to support any key type (including non-string keys for CBOR).\n *\n * Example:\n * const coseKeyMap = typedMap([\n * [CoseKeyParameter.KeyType, z.number()],\n * [CoseKeyParameter.Curve, z.number()],\n * [CoseKeyParameter.X, z.instanceof(Uint8Array)]\n * ] as const)\n *\n * The resulting schema validates a Map and transforms it to TypedMap<Schema, never>.\n */\nexport function typedMap<const Entries extends EntriesBase>(\n entries: Entries,\n {\n allowAdditionalKeys = true,\n keyLabels,\n encode,\n decode,\n }: {\n /**\n * Whether to allow additional keys in the typed map\n *\n * @default true\n */\n allowAdditionalKeys?: boolean\n\n /**\n * Human-readable names for the map's keys, used in validation errors so that a bare CBOR\n * label (`Expected key '4' to be defined.`) is not all a reader gets.\n *\n * A numeric TypeScript enum can be passed straight in — its reverse mapping supplies the\n * names — and several can be merged with a spread:\n *\n * typedMap(entries, { keyLabels: { ...RegisteredCwtClaimKey, ...StatusListCwtClaimKey } })\n *\n * An explicit record (`{ 4: 'exp' }`) works too. Keys with no name keep their raw label.\n */\n keyLabels?: Record<string | number, unknown>\n\n /**\n * Allows overriding the encode function. The original encode method is passed as second\n * argument, so you can use this method to pre/post process\n */\n encode?: (\n decoded: TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>,\n originalEncode: (decoded: TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>) => Map<unknown, unknown>\n ) => Map<unknown, unknown>\n\n /**\n * Allows overriding the decode function. The original decode method is passed as second\n * argument, so you can use this method to pre/post process\n */\n decode?: (\n encoded: Map<unknown, unknown>,\n originalDecode: (decoded: Map<unknown, unknown>) => TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>\n ) => TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>\n } = {}\n) {\n // Create a set of required keys (non-optional) for validation\n const requiredKeys = entries.filter(([, valueSchema]) => !isExactOptional(valueSchema)).map(([key]) => key)\n\n const schemaMap = new Map(entries)\n\n const labelFor = (key: string | number) => keyLabel(key, keyLabels)\n\n const originalEncode = (decoded: TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>) => decoded.toMap()\n const originalDecode = (encoded: Map<unknown, unknown>) =>\n TypedMap.fromMap<InferredSchema<Entries>, OptionalKeys<Entries>>(encoded)\n\n return z.codec(\n // Input is untyped map\n z.map(z.unknown(), z.unknown()),\n // Output is typed map\n z.instanceof<typeof TypedMap<InferredSchema<Entries>, OptionalKeys<Entries>>>(TypedMap).superRefine((map, ctx) => {\n // Check there's no additional keys in the map if not allowed\n const additionalKeys = Array.from(map.keys()).filter((key) => !schemaMap.has(key as string | number))\n if (additionalKeys.length > 0 && !allowAdditionalKeys) {\n for (const additionalKey of additionalKeys) {\n if (typeof additionalKey !== 'string' && typeof additionalKey !== 'number') {\n ctx.addIssue({\n code: 'invalid_key',\n origin: 'map',\n continue: true,\n path: [],\n input: map,\n issues: [],\n message: 'Key found in map that is not a string or number',\n })\n } else {\n ctx.addIssue({\n code: 'invalid_key',\n origin: 'map',\n continue: true,\n path: [additionalKey],\n input: map,\n issues: [],\n message: `Unexpected key '${labelFor(additionalKey)}' found in map, additional keys are not allowed.`,\n })\n }\n }\n }\n\n for (const [key, valueSchema] of schemaMap.entries()) {\n const hasKey = map.has(key)\n const value = map.get(key)\n\n if (!hasKey && requiredKeys.includes(key)) {\n ctx.addIssue({\n code: 'invalid_value',\n continue: true,\n message: `Expected key '${labelFor(key)}' to be defined.`,\n // NOTE: stringified for the same reason as the value issues below\n path: [`${key}`],\n values: [],\n input: value,\n })\n continue\n }\n\n // If key is not in the map, and also not required, skip validation\n if (!hasKey && !requiredKeys.includes(key)) {\n continue\n }\n\n const parseResult = valueSchema.safeParse(value)\n if (!parseResult.success) {\n for (const issue of parseResult.error.issues) {\n ctx.addIssue({\n ...issue,\n // NOTE: if we use numbers, zod-validation-error will use \"index\", thinking\n // it's an array, that's confusing. The value schema owns the message, so the\n // key's name has to travel on the path.\n path: [labelFor(key), ...issue.path],\n } as zCore.$ZodSuperRefineIssue)\n }\n }\n }\n }),\n {\n decode: (input) => (decode ? decode(input, originalDecode) : originalDecode(input)),\n encode: (output) => (encode ? encode(output, originalEncode) : originalEncode(output)),\n }\n )\n}\n","// biome-ignore format: no explanation\nclass CoseError extends Error {\n // NOTE: declared explicitly rather than passing `{ cause }` to `super`, as the\n // project targets ES2020 and `Error.cause` was only added in ES2022.\n public readonly cause?: unknown\n\n constructor(message: string = new.target.name, options?: { cause?: unknown }) {\n super(message)\n this.name = new.target.name\n this.cause = options?.cause\n }\n}\n\nexport class CoseUnsupportedMacError extends CoseError {}\nexport class CoseInvalidSignatureError extends CoseError {}\nexport class CoseInvalidAlgorithmError extends CoseError {}\nexport class CosePayloadMustBeNullError extends CoseError {}\nexport class CosePayloadMustBeDefinedError extends CoseError {}\nexport class CosePayloadInvalidStructureError extends CoseError {}\nexport class CoseInvalidTypeForKeyError extends CoseError {}\nexport class CoseInvalidValueForKtyError extends CoseError {}\nexport class CoseInvalidKtyForRawError extends CoseError {}\nexport class CoseXNotDefinedError extends CoseError {}\nexport class CoseYNotDefinedError extends CoseError {}\nexport class CoseDNotDefinedError extends CoseError {}\nexport class CoseKNotDefinedError extends CoseError {}\nexport class CoseEphemeralMacKeyIsRequiredError extends CoseError {}\nexport class CoseCertificateNotFoundError extends CoseError {}\n\n/**\n * RFC 9360: the end-entity certificate \"MUST be integrity protected by COSE\". An `x5chain` in the\n * unprotected header is therefore only accepted when a protected `x5t` matches its leaf.\n */\nexport class CoseX5ChainNotBoundError extends CoseError {}\nexport class CoseKeyTypeNotSupportedForPrivateKeyExtractionError extends CoseError {}\n\n/** The CWT carries a detached payload (`null`), which cannot be decoded into a claims set. */\nexport class CwtDetachedPayloadError extends CoseError {}\n\n/** The CWT payload is not a valid claims set for the CWT type it was decoded as. */\nexport class CwtPayloadDecodeError extends CoseError {}\n\n/** The CWT carries neither a signature nor an authentication tag, so there is nothing to verify. */\nexport class CwtNotSignedError extends CoseError {}\n\n/** No verification context was provided for the COSE structure the CWT is carried in. */\nexport class CwtMissingVerifyContextError extends CoseError {}\n\n/**\n * A claim required by the profile the token is verified against is missing, a claim does not match\n * the value it was expected to have, or the token is outside its validity window.\n */\nexport class CwtClaimVerificationError extends CoseError {}\n","/**\n *\n * Registered CWT claim keys\n * @see https://www.rfc-editor.org/rfc/rfc8392#section-3.1\n *\n */\nexport enum RegisteredCwtClaimKey {\n Issuer = 1,\n Subject = 2,\n Audience = 3,\n ExpirationTime = 4,\n NotBefore = 5,\n IssuedAt = 6,\n CwtId = 7,\n}\n","import { dateToSeconds, secondsToDate } from '@owf/identity-common'\nimport z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport {\n type AnyTypedMap,\n type EntriesBase,\n type ExtendedEntries,\n extendTypedMapEntries,\n keyLabel,\n TypedMap,\n typedMap,\n} from '../../utils/typed-map.js'\nimport { zUint8Array } from '../../utils/zod.js'\nimport { CwtClaimVerificationError } from '../error.js'\nimport { RegisteredCwtClaimKey } from './default.js'\n\n/**\n * A CWT NumericDate: the number of seconds since the epoch, as an integer or a floating-point\n * number.\n *\n * @see https://www.rfc-editor.org/rfc/rfc8392#section-2\n */\nexport const zCwtNumericDate = z.number()\n\n/**\n * The registered CWT claims (RFC 8392 Section 3.1), as `typedMap` entries.\n *\n * All of them are optional: RFC 8392 does not require any claim to be present, and which claims a\n * token must carry is decided by the CWT type. A specific CWT builds on these with\n * {@link extendCwtPayloadClaims}, and can make a claim required by redeclaring it.\n */\nexport const cwtPayloadClaimEntries = [\n [RegisteredCwtClaimKey.Issuer, z.string().exactOptional()],\n [RegisteredCwtClaimKey.Subject, z.string().exactOptional()],\n // RFC 8392 defines `aud` as a single StringOrURI, but tokens in the wild follow JWT and also use\n // an array, so both are accepted.\n [RegisteredCwtClaimKey.Audience, z.union([z.string(), z.array(z.string())]).exactOptional()],\n [RegisteredCwtClaimKey.ExpirationTime, zCwtNumericDate.exactOptional()],\n [RegisteredCwtClaimKey.NotBefore, zCwtNumericDate.exactOptional()],\n [RegisteredCwtClaimKey.IssuedAt, zCwtNumericDate.exactOptional()],\n [RegisteredCwtClaimKey.CwtId, zUint8Array.exactOptional()],\n] as const\n\n/**\n * Schema for a CWT Claims Set carrying only the registered claims. Additional (application or\n * private use) claims are allowed through untyped.\n */\nexport const cwtPayloadSchema = typedMap(cwtPayloadClaimEntries, {\n allowAdditionalKeys: true,\n keyLabels: RegisteredCwtClaimKey,\n})\n\nexport type ExtendedCwtPayloadClaimEntries<Entries extends EntriesBase> = ExtendedEntries<\n typeof cwtPayloadClaimEntries,\n Entries\n>\n\n/**\n * Builds a claims schema for a specific CWT type: the registered CWT claims plus the given ones. An\n * entry reusing a registered claim key replaces it, which is how a CWT type makes an inherited claim\n * required or narrows its value.\n *\n * The registered claim names are used in validation errors out of the box. Pass `keyLabels` to name\n * the added claims too — a numeric TypeScript enum can be passed straight in.\n *\n * @example\n * ```ts\n * const statusListCwtPayloadSchema = extendCwtPayloadClaims(\n * [\n * // `sub` is optional in the registered claims, but required for a status list\n * [RegisteredCwtClaimKey.Subject, z.string()],\n * [StatusListCwtClaimKey.StatusList, z.instanceof(StatusListCbor)],\n * ] as const,\n * { keyLabels: StatusListCwtClaimKey }\n * )\n * ```\n */\nexport function extendCwtPayloadClaims<const Entries extends EntriesBase>(\n entries: Entries,\n {\n keyLabels,\n }: {\n /**\n * Human-readable names for the added claims, merged with the registered CWT claim names. See\n * the `keyLabels` option of `typedMap`.\n */\n keyLabels?: Record<string | number, unknown>\n } = {}\n): ReturnType<typeof typedMap<ExtendedCwtPayloadClaimEntries<Entries>>> {\n return typedMap(extendTypedMapEntries(cwtPayloadClaimEntries, entries), {\n allowAdditionalKeys: true,\n keyLabels: { ...RegisteredCwtClaimKey, ...keyLabels },\n })\n}\n\nexport type CwtPayloadEncodedStructure = z.input<typeof cwtPayloadSchema>\nexport type CwtPayloadDecodedStructure = z.output<typeof cwtPayloadSchema>\n\nexport type CreateCwtPayloadOptions = {\n issuer?: string\n subject?: string\n audience?: string | string[]\n expirationTime?: Date\n notBefore?: Date\n issuedAt?: Date\n cwtId?: Uint8Array\n\n /**\n * Claims that are not part of the registered CWT claims. Added after the registered claims, in\n * iteration order.\n */\n additionalClaims?: Map<number | string, unknown>\n}\n\n/**\n * Builds the claims map for the registered CWT claims from {@link CreateCwtPayloadOptions}, so a CWT\n * type can reuse it while adding its own claims. Claims that were not provided are omitted rather\n * than set to `undefined`, since an explicit `undefined` would be encoded into the CBOR map.\n */\nexport function cwtPayloadClaimsFromOptions(options: CreateCwtPayloadOptions): Map<number | string, unknown> {\n const claims = new Map<number | string, unknown>()\n\n if (options.issuer !== undefined) claims.set(RegisteredCwtClaimKey.Issuer, options.issuer)\n if (options.subject !== undefined) claims.set(RegisteredCwtClaimKey.Subject, options.subject)\n if (options.audience !== undefined) claims.set(RegisteredCwtClaimKey.Audience, options.audience)\n if (options.expirationTime !== undefined) {\n claims.set(RegisteredCwtClaimKey.ExpirationTime, dateToSeconds(options.expirationTime))\n }\n if (options.notBefore !== undefined) claims.set(RegisteredCwtClaimKey.NotBefore, dateToSeconds(options.notBefore))\n if (options.issuedAt !== undefined) claims.set(RegisteredCwtClaimKey.IssuedAt, dateToSeconds(options.issuedAt))\n if (options.cwtId !== undefined) claims.set(RegisteredCwtClaimKey.CwtId, options.cwtId)\n\n for (const [key, value] of options.additionalClaims ?? new Map()) {\n claims.set(key, value)\n }\n\n return claims\n}\n\n/**\n * Names a claim for an error message, the same way a claims schema names it in a validation error:\n * `'Subject (2)'` for a registered claim, and the bare label for any other unless `keyLabels` has a\n * name for it.\n *\n * @see the `keyLabels` option of `typedMap`\n */\nexport function claimLabel(key: number | string, keyLabels?: Record<string | number, unknown>): string {\n return `'${keyLabel(key, { ...RegisteredCwtClaimKey, ...keyLabels })}'`\n}\n\n/** The options {@link CwtPayload.verifyClaims} takes. */\nexport type VerifyCwtClaimsOptions = {\n /** The time the token is verified at. Defaults to the current time. */\n now?: Date\n\n /**\n * Clock tolerance applied to `exp`, `nbf` and `iat`, in seconds. Defaults to 30, which keeps a\n * token that only just expired — or that was issued a moment ago by a slightly fast clock —\n * usable across the small clock differences typical between issuer and verifier.\n */\n skewSeconds?: number\n\n /**\n * The claims that must be present. A claim listed here is rejected when absent; a claim that is\n * absent and not listed is simply not checked. Any claim key can be required, not only a\n * registered one, since presence is checked against the claims map.\n */\n requiredClaims?: ReadonlyArray<RegisteredCwtClaimKey | number | string>\n\n /** The value(s) `iss` (1) is accepted with. Not checked when the token carries no `iss`. */\n expectedIssuer?: string | string[]\n\n /** The value(s) `sub` (2) is accepted with. Not checked when the token carries no `sub`. */\n expectedSubject?: string | string[]\n\n /**\n * The value(s) `aud` (3) is accepted with. The token is accepted when any of its audiences is\n * one of these. Not checked when the token carries no `aud`.\n */\n expectedAudience?: string | string[]\n\n /** When false, `exp` is not compared against `now`. Its presence is still checked. */\n checkExpirationTime?: boolean\n\n /** When false, `nbf` is not compared against `now`. Its presence is still checked. */\n checkNotBefore?: boolean\n\n /** When false, `iat` is not compared against `now`. Its presence is still checked. */\n checkIssuedAt?: boolean\n\n /**\n * Human-readable names for the claim keys, used in errors so that a bare CBOR label is not all a\n * reader gets. The registered CWT claim names are always available; pass the ones a CWT type adds\n * on top of them, the same way a claims schema is given them.\n *\n * @see the `keyLabels` option of `typedMap`\n */\n keyLabels?: Record<string | number, unknown>\n}\n\nconst asArray = (value: string | string[]) => (Array.isArray(value) ? value : [value])\nconst quoted = (values: string[]) => values.map((value) => `'${value}'`).join(', ')\n\n// biome-ignore lint/suspicious/noExplicitAny: inferring from an unconstrained TypedMap\ntype ClaimsSchemaOf<Structure> = Structure extends TypedMap<infer Schema, any> ? Schema : never\n// biome-ignore lint/suspicious/noExplicitAny: inferring from an unconstrained TypedMap\ntype OptionalClaimKeysOf<Structure> = Structure extends TypedMap<any, infer Optional> ? Optional : never\n\n/**\n * The shape a registered CWT claim always has, taken from the registered claims schema itself, and\n * `unknown` for any other claim key. Widened with `undefined`, since a registered claim is optional\n * unless the CWT type redeclares it as required.\n *\n * Every claims schema is built on `cwtPayloadClaimEntries`, so a registered claim is validated to\n * this shape whether or not the CWT type redeclares it. {@link ClaimValue} intersects it with the\n * type the CWT type's own schema gives the claim, which is what lets this class read its registered\n * claims while `Structure` is still generic: the schema's type is unresolved until `Structure` is\n * known, but the registered shape is not.\n */\ntype RegisteredClaimShape<Key extends number | string> = Key extends keyof ClaimsSchemaOf<CwtPayloadDecodedStructure>\n ? ClaimsSchemaOf<CwtPayloadDecodedStructure>[Key] | undefined\n : unknown\n\n/**\n * The value type of a single claim in a claims map: the schema's type for a claim the CWT type\n * declares (widened with `undefined` when it declares it as optional), and `unknown` for any other\n * claim key, since those are carried through unvalidated.\n *\n * Intersected with {@link RegisteredClaimShape}, which narrows nothing for a resolved schema —\n * `string & (string | undefined)` is `string` — and carries the registered shape through while\n * `Structure` is generic.\n */\nexport type ClaimValue<Structure, Key extends number | string> = RegisteredClaimShape<Key> &\n (Key extends keyof ClaimsSchemaOf<Structure>\n ? Key extends OptionalClaimKeysOf<Structure>\n ? ClaimsSchemaOf<Structure>[Key] | undefined\n : ClaimsSchemaOf<Structure>[Key]\n : unknown)\n\n/**\n * The type of a date accessor for a NumericDate claim: `Date` when the CWT type declares the claim\n * as required, and `Date | undefined` otherwise (including for a claim the type does not declare,\n * whose value is `unknown`). This is what makes the inherited date accessors narrow automatically in\n * a subtype that redeclares the claim as required.\n */\nexport type DateClaimValue<Structure, Key extends number | string> =\n undefined extends ClaimValue<Structure, Key> ? Date | undefined : Date\n\n/**\n * A CWT Claims Set (RFC 8392), with the registered claims typed.\n *\n * A specific CWT type extends this class and overrides {@link encodingSchema} with a schema built by\n * {@link extendCwtPayloadClaims}, passing the resulting decoded structure as `Structure`. The\n * inherited accessors then narrow along with the schema: a claim the subtype declares as required is\n * no longer `undefined`, neither on `claims.get(...)` nor on the accessor for it.\n *\n * @template Structure - The decoded claims map. Defaults to the registered CWT claims.\n */\nexport class CwtPayload<Structure extends AnyTypedMap = CwtPayloadDecodedStructure> extends CborStructure<\n CwtPayloadEncodedStructure,\n Structure\n> {\n // NOTE: widened to `z.ZodType` so a subtype can override it with its own (structurally unrelated)\n // claims schema without breaking static-side assignability.\n public static override get encodingSchema(): z.ZodType {\n return cwtPayloadSchema\n }\n\n /**\n * The decoded claims map. Typed for the claims this CWT type declares, and open for any other\n * claim key.\n */\n public get claims(): Structure {\n return this.structure\n }\n\n /**\n * Reads a claim by its key, typed from this CWT type's claims schema. A claim the schema does not\n * declare is returned as `unknown`, as it was carried through unvalidated.\n */\n public getClaim<Key extends number | string>(key: Key): ClaimValue<Structure, Key> {\n return this.structure.get(key) as ClaimValue<Structure, Key>\n }\n\n /** `iss` (1) */\n public get issuer(): ClaimValue<Structure, RegisteredCwtClaimKey.Issuer> {\n return this.getClaim(RegisteredCwtClaimKey.Issuer)\n }\n\n /** `sub` (2) */\n public get subject(): ClaimValue<Structure, RegisteredCwtClaimKey.Subject> {\n return this.getClaim(RegisteredCwtClaimKey.Subject)\n }\n\n /** `aud` (3) */\n public get audience(): ClaimValue<Structure, RegisteredCwtClaimKey.Audience> {\n return this.getClaim(RegisteredCwtClaimKey.Audience)\n }\n\n /** `exp` (4) */\n public get expirationTime(): DateClaimValue<Structure, RegisteredCwtClaimKey.ExpirationTime> {\n const expirationTime = this.getClaim(RegisteredCwtClaimKey.ExpirationTime)\n return (typeof expirationTime === 'number' ? secondsToDate(expirationTime) : undefined) as DateClaimValue<\n Structure,\n RegisteredCwtClaimKey.ExpirationTime\n >\n }\n\n /** `nbf` (5) */\n public get notBefore(): DateClaimValue<Structure, RegisteredCwtClaimKey.NotBefore> {\n const notBefore = this.getClaim(RegisteredCwtClaimKey.NotBefore)\n return (typeof notBefore === 'number' ? secondsToDate(notBefore) : undefined) as DateClaimValue<\n Structure,\n RegisteredCwtClaimKey.NotBefore\n >\n }\n\n /** `iat` (6) */\n public get issuedAt(): DateClaimValue<Structure, RegisteredCwtClaimKey.IssuedAt> {\n const issuedAt = this.getClaim(RegisteredCwtClaimKey.IssuedAt)\n return (typeof issuedAt === 'number' ? secondsToDate(issuedAt) : undefined) as DateClaimValue<\n Structure,\n RegisteredCwtClaimKey.IssuedAt\n >\n }\n\n /** `cti` (7) */\n public get cwtId(): ClaimValue<Structure, RegisteredCwtClaimKey.CwtId> {\n return this.getClaim(RegisteredCwtClaimKey.CwtId)\n }\n\n /**\n * Verifies this claims set: that the claims the CWT type requires are present, that `iss` / `sub`\n * / `aud` are the expected ones, and that the token is within its validity window (`exp`, `nbf`\n * and `iat`, compared against `now` with a clock skew tolerance).\n *\n * Which claims a CWT must carry and what they must contain is decided by the CWT type, not by\n * RFC 8392, so nothing is required unless `requiredClaims` says so. A CWT type overrides this\n * method to apply its own rules, and calls `super.verifyClaims` with them.\n *\n * This checks the claims only. The signature or authentication tag over them is verified\n * separately — `Cwt.verify` does both.\n *\n * @throws CwtClaimVerificationError if a required claim is missing, a claim does not match what\n * was expected, or the token is outside its validity window.\n *\n * @see https://www.rfc-editor.org/rfc/rfc8392#section-3.1\n */\n public verifyClaims({\n now = new Date(),\n skewSeconds = 30,\n requiredClaims,\n expectedIssuer,\n expectedSubject,\n expectedAudience,\n checkExpirationTime = true,\n checkNotBefore = true,\n checkIssuedAt = true,\n keyLabels,\n }: VerifyCwtClaimsOptions = {}): void {\n const skewMs = skewSeconds * 1000\n\n // Presence is checked against the claims map rather than against the accessors, so that a claim\n // this CWT type adds — which has no accessor here — can be required too.\n for (const key of requiredClaims ?? []) {\n if (!this.structure.has(key)) {\n throw new CwtClaimVerificationError(`The token has no ${claimLabel(key, keyLabels)} claim, which is required`)\n }\n }\n\n verifyClaimMatches(RegisteredCwtClaimKey.Issuer, this.issuer, expectedIssuer, keyLabels)\n verifyClaimMatches(RegisteredCwtClaimKey.Subject, this.subject, expectedSubject, keyLabels)\n verifyAudienceMatches(this.audience, expectedAudience, keyLabels)\n\n // `exp` is the first instant the token is no longer valid, so it is an upper bound shifted\n // forward by the skew: a token that expired within the tolerance is still accepted.\n const expirationTime: Date | undefined = this.expirationTime\n if (expirationTime !== undefined && checkExpirationTime && new Date(expirationTime.getTime() + skewMs) <= now) {\n throw new CwtClaimVerificationError(\n `The ${claimLabel(RegisteredCwtClaimKey.ExpirationTime, keyLabels)} claim '${expirationTime.toISOString()}' is in the past (compared to '${now.toISOString()}'), and therefore not valid`\n )\n }\n\n if (checkNotBefore) {\n verifyClaimNotInFuture(RegisteredCwtClaimKey.NotBefore, this.notBefore, now, skewMs, keyLabels)\n }\n if (checkIssuedAt) {\n verifyClaimNotInFuture(RegisteredCwtClaimKey.IssuedAt, this.issuedAt, now, skewMs, keyLabels)\n }\n }\n\n public static create(options: CreateCwtPayloadOptions = {}) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(TypedMap.fromMap(cwtPayloadClaimsFromOptions(options)))\n }\n}\n\nfunction verifyClaimMatches(\n key: RegisteredCwtClaimKey,\n value: string | undefined,\n expected: string | string[] | undefined,\n keyLabels?: Record<string | number, unknown>\n) {\n if (value === undefined || expected === undefined) return\n\n const expectedValues = asArray(expected)\n if (!expectedValues.includes(value)) {\n throw new CwtClaimVerificationError(\n `The ${claimLabel(key, keyLabels)} claim '${value}' does not match the expected value ${quoted(expectedValues)}`\n )\n }\n}\n\n/** `aud` may hold several audiences, and the token is for us as soon as one of them is expected. */\nfunction verifyAudienceMatches(\n audience: string | string[] | undefined,\n expected: string | string[] | undefined,\n keyLabels?: Record<string | number, unknown>\n) {\n if (audience === undefined || expected === undefined) return\n\n const audiences = asArray(audience)\n const expectedValues = asArray(expected)\n\n if (!audiences.some((value) => expectedValues.includes(value))) {\n throw new CwtClaimVerificationError(\n `The ${claimLabel(RegisteredCwtClaimKey.Audience, keyLabels)} claim ${quoted(audiences)} does not match the expected value ${quoted(expectedValues)}`\n )\n }\n}\n\n/**\n * `nbf` and `iat` are lower bounds on the validity window, so they are shifted back by the skew: a\n * token whose validity starts within the tolerance is already accepted.\n */\nfunction verifyClaimNotInFuture(\n key: RegisteredCwtClaimKey,\n value: Date | undefined,\n now: Date,\n skewMs: number,\n keyLabels?: Record<string | number, unknown>\n) {\n if (value === undefined) return\n\n if (new Date(value.getTime() - skewMs) > now) {\n throw new CwtClaimVerificationError(\n `The ${claimLabel(key, keyLabels)} claim '${value.toISOString()}' is in the future (compared to '${now.toISOString()}'), and therefore not valid`\n )\n }\n}\n\n/**\n * A {@link CwtPayload} with any claims schema. Used as a generic bound, because `TypedMap` is\n * invariant in its schema and a subtype's claims map is therefore not assignable to the base one.\n */\n// biome-ignore lint/suspicious/noExplicitAny: intentionally unconstrained, used as a generic bound\nexport type AnyCwtPayload = CwtPayload<any>\n","/**\n *\n * Registered CWT header keys\n *\n */\nexport enum RegisteredCwtHeaderClaimKey {\n Algorithm = 1,\n Critical = 2,\n ContentType = 3,\n KeyId = 4,\n Iv = 5,\n PartialIv = 6,\n CounterSignature = 7,\n CounterSignature0 = 9,\n CounterSignatureV2 = 11,\n CounterSignature0V2 = 12,\n Typ = 16,\n X5Bag = 32,\n X5Chain = 33,\n X5T = 34,\n X5U = 35,\n}\n\nexport enum SignatureAlgorithm {\n EdDSA = -8,\n ES256 = -7,\n ES384 = -35,\n ES512 = -36,\n /** RFC 9864 § 2.1: ECDSA using P-256 and SHA-256. */\n ESP256 = -9,\n /** RFC 9864 § 2.1: ECDSA using P-384 and SHA-384. */\n ESP384 = -51,\n /** RFC 9864 § 2.1: ECDSA using P-521 and SHA-512. */\n ESP512 = -52,\n /** RFC 9864 § 2.2: EdDSA using the Ed25519 parameter set. */\n Ed25519 = -19,\n /** RFC 9864 § 2.2: EdDSA using the Ed448 parameter set. */\n Ed448 = -53,\n PS256 = -37,\n PS384 = -38,\n PS512 = -39,\n RS256 = -257,\n RS384 = -258,\n RS512 = -259,\n}\n\nexport enum MacAlgorithm {\n HS256 = 5,\n HS384 = 6,\n HS512 = 7,\n}\n\nexport enum EncryptionAlgorithm {\n A128GCM = 1,\n A192GCM = 2,\n A256GCM = 3,\n Direct = -6,\n}\n\nexport type DigestAlgorithm = 'SHA-256' | 'SHA-384' | 'SHA-512'\n","import z from 'zod'\nimport {\n type EntriesBase,\n type ExtendedEntries,\n extendTypedMapEntries,\n type TypedMap,\n typedMap,\n} from '../../utils/typed-map.js'\nimport { zUint8Array } from '../../utils/zod.js'\nimport { RegisteredCwtHeaderClaimKey } from './defaults.js'\n\n// A COSE label is an integer (registry) or a text string (private use).\nconst zCoseLabel = z.union([z.number(), z.string()])\n// COSE_X509: a single certificate (bstr) or a chain (array of bstr). Used by x5bag/x5chain.\nconst zCertOrChain = z.union([zUint8Array, z.array(zUint8Array)])\n\n/**\n * The known COSE header claims (RFC 9052 Section 3.1 / RFC 9360 / RFC 9596 / the IANA COSE Header\n * Parameters registry), as `typedMap` entries.\n *\n * Exported separately from {@link coseHeaderClaimsSchema} so a profile can build on them with\n * {@link extendCoseHeaderClaims}.\n */\nexport const coseHeaderClaimEntries = [\n [RegisteredCwtHeaderClaimKey.Algorithm, zCoseLabel.exactOptional()],\n [RegisteredCwtHeaderClaimKey.Critical, z.array(zCoseLabel).exactOptional()],\n [RegisteredCwtHeaderClaimKey.ContentType, zCoseLabel.exactOptional()],\n [RegisteredCwtHeaderClaimKey.KeyId, zUint8Array.exactOptional()],\n [RegisteredCwtHeaderClaimKey.Iv, zUint8Array.exactOptional()],\n [RegisteredCwtHeaderClaimKey.PartialIv, zUint8Array.exactOptional()],\n // RFC 9596: a media type as a text string, or a CoAP Content-Format integer.\n [RegisteredCwtHeaderClaimKey.Typ, zCoseLabel.exactOptional()],\n [RegisteredCwtHeaderClaimKey.X5Bag, zCertOrChain.exactOptional()],\n [RegisteredCwtHeaderClaimKey.X5Chain, zCertOrChain.exactOptional()],\n [RegisteredCwtHeaderClaimKey.X5T, z.array(z.unknown()).exactOptional()],\n [RegisteredCwtHeaderClaimKey.X5U, z.string().exactOptional()],\n] as const\n\n/**\n * Schema for the known COSE header claims. Shared by the protected and unprotected header\n * structures.\n *\n * Each registered label is typed to its CBOR shape; in particular `kid` (4) is a bstr (`Uint8Array`),\n * so a header carrying a `kid` whose value is not a bstr (e.g. a malformed `{ 4: undefined }`) is\n * rejected at decode for every Sign1-derived structure. Additional (unregistered or private-use)\n * labels are allowed through (`allowAdditionalKeys`).\n */\nexport const coseHeaderClaimsSchema = typedMap(coseHeaderClaimEntries, {\n allowAdditionalKeys: true,\n keyLabels: RegisteredCwtHeaderClaimKey,\n})\n\nexport type CoseHeaderClaims = z.infer<typeof coseHeaderClaimsSchema>\n\nexport type ExtendedCoseHeaderClaimEntries<Entries extends EntriesBase> = ExtendedEntries<\n typeof coseHeaderClaimEntries,\n Entries\n>\n\n/**\n * Builds a header claims schema for a specific COSE/CWT profile: the registered COSE header claims\n * plus the given ones. An entry reusing a registered label replaces it, so a profile can also\n * narrow an existing claim (e.g. requiring `typ` to be a specific media type).\n *\n * The registered header claim names are used in validation errors out of the box. Pass `keyLabels`\n * to name the added labels too — a numeric TypeScript enum can be passed straight in.\n *\n * @example\n * ```ts\n * const statusListHeaderClaimsSchema = extendCoseHeaderClaims([\n * [RegisteredCwtHeaderClaimKey.Typ, z.literal('application/statuslist+cwt')],\n * ] as const)\n * ```\n */\nexport function extendCoseHeaderClaims<const Entries extends EntriesBase>(\n entries: Entries,\n {\n keyLabels,\n }: {\n /**\n * Human-readable names for the added header labels, merged with the registered COSE header\n * claim names. See the `keyLabels` option of `typedMap`.\n */\n keyLabels?: Record<string | number, unknown>\n } = {}\n): ReturnType<typeof typedMap<ExtendedCoseHeaderClaimEntries<Entries>>> {\n return typedMap(extendTypedMapEntries(coseHeaderClaimEntries, entries), {\n allowAdditionalKeys: true,\n keyLabels: { ...RegisteredCwtHeaderClaimKey, ...keyLabels },\n })\n}\n\n// Widen a typed-map type to also allow access to any other integer label.\ntype OpenIntegerKeys<T> =\n T extends TypedMap<infer Schema, infer Optional> ? TypedMap<Schema & Record<number, unknown>, Optional> : never\n\n/**\n * Read/write view over a COSE header map: the typed claims above plus open access to any other\n * integer label, because COSE headers are open-ended (unregistered and private-use labels are valid).\n * The typed claims are still validated at decode by `coseHeaderClaimsSchema`; this view only governs\n * typed access.\n */\nexport type CoseHeaders = OpenIntegerKeys<CoseHeaderClaims>\n\n/**\n * The {@link CoseHeaders} view for a profile-specific header claims schema, i.e. one built with\n * {@link extendCoseHeaderClaims}.\n */\nexport type CoseHeadersFor<Schema extends z.ZodType> = OpenIntegerKeys<z.infer<Schema>>\n","import z from 'zod'\nimport {\n type AnyCborStructure,\n CborStructure,\n type CborStructureStaticThis,\n type EncodedStructureType,\n} from '../../cbor/cbor-structure.js'\nimport { cborDecode, cborEncode } from '../../cbor/parser.js'\nimport { type AnyTypedMap, TypedMap } from '../../utils/typed-map.js'\nimport { zUint8Array } from '../../utils/zod.js'\nimport { type CoseHeaders, coseHeaderClaimsSchema } from './header-claims.js'\n\n// Wire form: the header map is wrapped in a bstr (RFC 9052). `protectedHeadersDecodedStructure` is\n// the plain map carried inside that bstr, kept for backwards compatibility.\nexport const protectedHeadersEncodedStructure = zUint8Array\nexport const protectedHeadersDecodedStructure = z.map(z.number(), z.unknown())\n\nexport type ProtectedHeadersEncodedStructure = z.infer<typeof protectedHeadersEncodedStructure>\nexport type ProtectedHeadersDecodedStructure = z.infer<typeof coseHeaderClaimsSchema>\n\n/**\n * Wraps a header claims schema in the bstr the protected headers are carried in (RFC 9052), giving\n * the encoding schema for a {@link ProtectedHeaders} class.\n *\n * A profile subclasses `ProtectedHeaders` and overrides `encodingSchema` with this, passing a claims\n * schema built by `extendCoseHeaderClaims`. The headers are then validated against that schema\n * wherever the structure is built, the same way every other `CborStructure` validates itself.\n */\nexport function protectedHeadersSchema<ClaimsSchema extends z.ZodType>(\n claimsSchema: z.ZodCodec<z.ZodType, ClaimsSchema>\n) {\n return z.codec(protectedHeadersEncodedStructure, claimsSchema.out, {\n // TODO: Senders SHOULD encode a zero-length map as a zero-length string rather than as a zero-length map\n encode: (decoded) => cborEncode((decoded as AnyTypedMap).toMap()) as Uint8Array<ArrayBuffer>,\n decode: (encoded) =>\n TypedMap.fromMap(cborDecode(encoded) as Map<number, unknown>) as unknown as z.input<ClaimsSchema>,\n })\n}\n\nexport type ProtectedHeaderOptions = {\n protectedHeaders?: Map<number, unknown>\n}\n\n/**\n * The protected header map of a COSE structure.\n *\n * A profile that adds or narrows header labels subclasses this and overrides `encodingSchema` with\n * `protectedHeadersSchema(...)`, passing the type of the resulting map as `Headers`:\n *\n * ```ts\n * const claims = extendCoseHeaderClaims([[RegisteredCwtHeaderClaimKey.Typ, z.literal('application/example+cwt')]] as const)\n *\n * class ExampleProtectedHeaders extends ProtectedHeaders<CoseHeadersFor<typeof claims>> {\n * public static override get encodingSchema() {\n * return protectedHeadersSchema(claims)\n * }\n * }\n * ```\n *\n * Headers decoded from a token keep the bstr they came from, so that verification uses the bytes the\n * issuer signed rather than our re-encoding of them. See {@link originalEncodedStructure}.\n *\n * @template Headers - The typed view over the header map. Defaults to the registered COSE header\n * claims.\n */\nexport class ProtectedHeaders<Headers extends AnyTypedMap = CoseHeaders> extends CborStructure<\n ProtectedHeadersEncodedStructure,\n Headers\n> {\n /**\n * The bstr this was decoded from, kept so that it is what goes back into the `Sig_structure` /\n * `MAC_structure` (RFC 9052 puts the protected headers in as an opaque bstr, so what was signed\n * is the exact bytes the issuer sent). Re-encoding the map instead is not byte-preserving for\n * input that is valid CBOR but not the form we would write — a non-shortest-form integer, an\n * indefinite-length map, a float, a bignum, a tag 0 date — and the signature over such a token\n * would fail to verify for no visible reason.\n *\n * Dropped as soon as the header map is changed, since the bytes no longer describe it.\n *\n * @see https://datatracker.ietf.org/doc/rfc9052/#section-4.4\n */\n private originalEncodedStructure?: ProtectedHeadersEncodedStructure\n\n public static override get encodingSchema(): z.ZodType {\n return protectedHeadersSchema(coseHeaderClaimsSchema)\n }\n\n public get headers(): Headers {\n return this.structure\n }\n\n /**\n * The header map as it goes on the wire: the bstr this was decoded from when it came from a\n * token and has not been changed since, and the encoded map otherwise.\n */\n public override get encodedStructure(): ProtectedHeadersEncodedStructure {\n return this.originalEncodedStructure ?? super.encodedStructure\n }\n\n /**\n * Drops the retained {@link originalEncodedStructure}, so that the headers are re-encoded the next\n * time they are used. Changing the header map does this on its own; call it after changing a\n * header *value* in place — `headers.get(x5chain)[0] = ...` — which the map cannot see.\n */\n public markModified() {\n this.originalEncodedStructure = undefined\n }\n\n public static override fromEncodedStructure<T extends AnyCborStructure>(\n this: CborStructureStaticThis<T>,\n encodedStructure: EncodedStructureType<T>\n ): T {\n // biome-ignore lint/complexity/noThisInStatic: `super` keeps `this` bound to the subclass it was called on, which is what constructs a profile's header class rather than this one\n const headers = super.fromEncodedStructure(encodedStructure) as T & ProtectedHeaders<AnyTypedMap>\n\n // NOTE: copied, because the decoder hands back a view onto the buffer the whole token was\n // decoded from.\n headers.originalEncodedStructure = new Uint8Array(encodedStructure as Uint8Array)\n headers.headers.onChange = () => headers.markModified()\n\n return headers\n }\n\n public static create(options: ProtectedHeaderOptions) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(TypedMap.fromMap(options.protectedHeaders ?? new Map()))\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport { type AnyTypedMap, TypedMap } from '../../utils/typed-map.js'\nimport { type CoseHeaders, coseHeaderClaimsSchema } from './header-claims.js'\n\n// Wire form: a plain map of integer label -> value (used by the COSE_Sign1 encoded schema).\nexport const unprotectedHeadersStructure = z.map(z.number(), z.unknown())\n\nexport type UnprotectedHeadersEncodedStructure = z.infer<typeof unprotectedHeadersStructure>\nexport type UnprotectedHeadersDecodedStructure = z.infer<typeof coseHeaderClaimsSchema>\n\n// Backwards-compatible alias for the wire structure.\nexport type UnprotectedHeadersStructure = UnprotectedHeadersEncodedStructure\n\nexport type UnprotectedHeaderOptions = {\n unprotectedHeaders?: UnprotectedHeadersEncodedStructure\n}\n\n/**\n * The unprotected header map of a COSE structure. Subclassed the same way as\n * {@link ProtectedHeaders}, except that the claims schema is the encoding schema directly, since\n * the unprotected headers are carried as a plain map rather than wrapped in a bstr.\n *\n * @template Headers - The typed view over the header map. See {@link ProtectedHeaders}.\n */\nexport class UnprotectedHeaders<Headers extends AnyTypedMap = CoseHeaders> extends CborStructure<\n UnprotectedHeadersEncodedStructure,\n Headers\n> {\n public static override get encodingSchema(): z.ZodType {\n return coseHeaderClaimsSchema\n }\n\n public get headers(): Headers {\n return this.structure\n }\n\n public static create(options: UnprotectedHeaderOptions) {\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(TypedMap.fromMap(options.unprotectedHeaders ?? new Map()))\n }\n}\n","import { compareBytes } from '@owf/identity-common'\nimport type { AnyTypedMap } from '../../utils/typed-map.js'\nimport { CoseX5ChainNotBoundError } from '../error.js'\nimport { type DigestAlgorithm, RegisteredCwtHeaderClaimKey } from './defaults.js'\nimport type { ProtectedHeaders } from './protected-headers.js'\nimport type { UnprotectedHeaders } from './unprotected-headers.js'\n\n/** SHA-256 in a COSE_CertHash (RFC 9360), as registered in RFC 9054. */\nconst COSE_SHA_256 = -16\n\nexport type X5ChainContext = {\n digest: (input: { digestAlgorithm: DigestAlgorithm; bytes: Uint8Array }) => Promise<Uint8Array> | Uint8Array\n}\n\n/**\n * The `x5chain` of a COSE structure, provided its end-entity certificate is integrity protected, as\n * RFC 9360 requires: read from the protected header, or else from the unprotected header when a\n * protected `x5t` matches its leaf. The unprotected header is not covered by the signature, so\n * without that binding the certificate could be replaced by another one for the same key.\n *\n * Only a SHA-256 `x5t` is supported.\n *\n * @returns the chain, leaf first, or `undefined` when neither header has an `x5chain`.\n * @throws CoseX5ChainNotBoundError if the `x5chain` is in the unprotected header but no protected `x5t` matches its leaf.\n */\nexport async function getIntegrityProtectedX5Chain(\n {\n protectedHeaders,\n unprotectedHeaders,\n }: { protectedHeaders: ProtectedHeaders<AnyTypedMap>; unprotectedHeaders: UnprotectedHeaders<AnyTypedMap> },\n ctx: X5ChainContext\n): Promise<Array<Uint8Array> | undefined> {\n const protectedX5Chain = normalizeX5Chain(protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.X5Chain))\n if (protectedX5Chain) return protectedX5Chain\n\n const x5chain = normalizeX5Chain(unprotectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.X5Chain))\n if (!x5chain) return undefined\n\n const x5t = protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.X5T)\n if (!Array.isArray(x5t) || x5t.length !== 2 || !(x5t[1] instanceof Uint8Array)) {\n throw new CoseX5ChainNotBoundError(\n 'The x5chain is in the unprotected header, but the protected header has no x5t that binds it'\n )\n }\n\n const [hashAlgorithm, expectedHash] = x5t as [unknown, Uint8Array]\n if (hashAlgorithm !== COSE_SHA_256) {\n throw new CoseX5ChainNotBoundError(\n `The x5t of the protected header uses hash algorithm '${String(hashAlgorithm)}', only SHA-256 (-16) is supported`\n )\n }\n\n const leafHash = await ctx.digest({ digestAlgorithm: 'SHA-256', bytes: x5chain[0] })\n if (!compareBytes(leafHash, expectedHash)) {\n throw new CoseX5ChainNotBoundError(\n 'The x5t of the protected header does not match the leaf of the x5chain in the unprotected header'\n )\n }\n\n return x5chain\n}\n\n/** COSE_X509 carries either a single certificate or a chain of them (RFC 9360). */\nfunction normalizeX5Chain(x5chain: unknown): Array<Uint8Array> | undefined {\n const chain = x5chain instanceof Uint8Array ? [x5chain] : x5chain\n if (!Array.isArray(chain) || chain.length === 0 || !chain.every((c) => c instanceof Uint8Array)) return undefined\n return chain\n}\n","export enum Curve {\n 'P-256' = 1,\n 'P-384' = 2,\n 'P-521' = 3,\n X25519 = 4,\n X448 = 5,\n Ed25519 = 6,\n Ed448 = 7,\n}\n","export enum KeyOps {\n Sign = 1,\n Verify = 2,\n Encrypt = 3,\n Decrypt = 4,\n WrapKey = 5,\n UnwrapKey = 6,\n DeriveKey = 7,\n DeriveBits = 8,\n MACCreate = 9,\n MACVerify = 10,\n}\n","export enum KeyType {\n Okp = 1,\n Ec = 2,\n Oct = 4,\n Reserved = 0,\n}\n","import { base64url } from '@owf/identity-common'\nimport { EncryptionAlgorithm, MacAlgorithm, SignatureAlgorithm } from '../headers/defaults'\nimport { Curve } from './curve'\nimport type { CoseKeyOptions } from './key'\nimport { KeyOps } from './key-operation'\nimport { KeyType } from './key-type'\n\nconst swapMap = (map: Record<string, string>) =>\n Object.fromEntries(Object.entries(map).map(([key, value]) => [value, key]))\n\nconst swapNestedMap = (nestedMap: Record<string, Record<string, unknown>>) =>\n Object.fromEntries(\n Object.entries(nestedMap).map(([category, mappings]) => [\n category,\n Object.fromEntries(Object.entries(mappings).map(([key, value]) => [value, key])),\n ])\n )\n\nconst jwkCoseKeyMap = {\n kty: {\n OKP: KeyType.Okp,\n EC: KeyType.Ec,\n OCT: KeyType.Oct,\n },\n crv: {\n 'P-256': Curve['P-256'],\n 'P-384': Curve['P-384'],\n 'P-521': Curve['P-521'],\n X25519: Curve.X25519,\n Ed25519: Curve.Ed25519,\n Ed448: Curve.Ed448,\n },\n alg: {\n EdDSA: SignatureAlgorithm.EdDSA,\n // RFC 9864 § 2.2: JOSE and COSE use the same names for the fully-specified EdDSA algorithms.\n Ed25519: SignatureAlgorithm.Ed25519,\n Ed448: SignatureAlgorithm.Ed448,\n ES256: SignatureAlgorithm.ES256,\n ES384: SignatureAlgorithm.ES384,\n ES512: SignatureAlgorithm.ES512,\n PS256: SignatureAlgorithm.PS256,\n PS384: SignatureAlgorithm.PS384,\n PS512: SignatureAlgorithm.PS512,\n RS256: SignatureAlgorithm.RS256,\n RS384: SignatureAlgorithm.RS384,\n RS512: SignatureAlgorithm.RS512,\n\n HS256: MacAlgorithm.HS256,\n HS384: MacAlgorithm.HS384,\n HS512: MacAlgorithm.HS512,\n\n A128GCM: EncryptionAlgorithm.A128GCM,\n A192GCM: EncryptionAlgorithm.A192GCM,\n A256GCM: EncryptionAlgorithm.A256GCM,\n Direct: EncryptionAlgorithm.Direct,\n },\n keyOps: {\n sign: KeyOps.Sign,\n verify: KeyOps.Verify,\n encrypt: KeyOps.Encrypt,\n decrypt: KeyOps.Decrypt,\n wrapKey: KeyOps.WrapKey,\n unwrapKey: KeyOps.UnwrapKey,\n deriveKey: KeyOps.DeriveKey,\n deriveBits: KeyOps.DeriveBits,\n mACCreate: KeyOps.MACCreate,\n mACVerify: KeyOps.MACVerify,\n },\n}\n\nconst swappedJwkCoseKeyMap = swapNestedMap(jwkCoseKeyMap)\n\n// RFC 9864 § 2.1: the JOSE ECDSA algorithms are fully specified, so the fully-specified COSE ECDSA\n// algorithms convert to the same JWA names. They are kept out of `jwkCoseKeyMap`, so that a JWA\n// `ES256` converts to the COSE `ES256` (-7) and not to `ESP256` (-9).\nconst coseKeyJwkMap: typeof swappedJwkCoseKeyMap = {\n ...swappedJwkCoseKeyMap,\n alg: {\n ...swappedJwkCoseKeyMap.alg,\n [SignatureAlgorithm.ESP256]: 'ES256',\n [SignatureAlgorithm.ESP384]: 'ES384',\n [SignatureAlgorithm.ESP512]: 'ES512',\n },\n}\n\nexport const jwkCoseOptionsMap: Record<string, keyof CoseKeyOptions> = {\n kty: 'keyType',\n kid: 'keyId',\n alg: 'algorithm',\n keyOps: 'keyOps',\n baseIv: 'baseIv',\n crv: 'curve',\n x: 'x',\n y: 'y',\n d: 'd',\n k: 'k',\n}\n\nexport const coseOptionsJwkMap = swapMap(jwkCoseOptionsMap)\n\nexport const jwkToCoseKey = {\n kty: (kty?: unknown) =>\n jwkCoseKeyMap.kty[(kty as string).toUpperCase() as keyof (typeof jwkCoseKeyMap)['kty']] ?? kty,\n crv: (crv?: unknown) => jwkCoseKeyMap.crv[crv as keyof (typeof jwkCoseKeyMap)['crv']] ?? crv,\n alg: (alg?: unknown) => jwkCoseKeyMap.alg[alg as keyof (typeof jwkCoseKeyMap)['alg']] ?? alg,\n kid: (kid?: unknown) => kid,\n keyOps: (keyOps?: unknown) =>\n Array.isArray(keyOps)\n ? keyOps?.map((ko) => jwkCoseKeyMap.keyOps[ko as keyof (typeof jwkCoseKeyMap)['keyOps']] ?? ko)\n : undefined,\n x: (s?: unknown) => (s && typeof s === 'string' ? base64url.decode(s) : undefined),\n y: (s?: unknown) => (s && typeof s === 'string' ? base64url.decode(s) : undefined),\n d: (s?: unknown) => (s && typeof s === 'string' ? base64url.decode(s) : undefined),\n k: (s?: unknown) => (s && typeof s === 'string' ? base64url.decode(s) : undefined),\n}\n\nexport const coseKeyToJwkClaim = {\n keyType: (keyType: KeyType) => coseKeyJwkMap.kty[keyType],\n keyId: (keyId: unknown) => keyId,\n algorithm: (algorithm?: SignatureAlgorithm | MacAlgorithm) => (algorithm ? coseKeyJwkMap.alg[algorithm] : undefined),\n keyOps: (keyOps?: unknown) =>\n keyOps && Array.isArray(keyOps) ? keyOps.map((ko) => coseKeyJwkMap.keyOps[ko]) : undefined,\n baseIv: (baseIv?: unknown) => baseIv,\n curve: (curve?: Curve) => (curve ? coseKeyJwkMap.crv[curve] : undefined),\n x: (x?: Uint8Array) => (x ? base64url.encode(x) : undefined),\n y: (y?: Uint8Array) => (y ? base64url.encode(y) : undefined),\n d: (d?: Uint8Array) => (d ? base64url.encode(d) : undefined),\n k: (k?: Uint8Array) => (k ? base64url.encode(k) : undefined),\n}\n","import { bytesToString, concatBytes, stringToBytes } from '@owf/identity-common'\nimport { z } from 'zod'\nimport { CborStructure } from '../../cbor'\nimport { TypedMap, typedMap } from '../../utils/typed-map'\nimport { zUint8Array } from '../../utils/zod'\nimport {\n CoseDNotDefinedError,\n CoseInvalidKtyForRawError,\n CoseInvalidValueForKtyError,\n CoseKeyTypeNotSupportedForPrivateKeyExtractionError,\n CoseKNotDefinedError,\n CoseXNotDefinedError,\n CoseYNotDefinedError,\n} from '../error'\nimport type { MacAlgorithm, SignatureAlgorithm } from '../headers'\nimport { Curve } from './curve'\nimport { coseKeyToJwkClaim, coseOptionsJwkMap, jwkCoseOptionsMap, jwkToCoseKey } from './jwk'\nimport { KeyOps } from './key-operation'\nimport { KeyType } from './key-type'\n\nexport enum CoseKeyParameter {\n KeyType = 1,\n KeyId = 2,\n Algorithm = 3,\n KeyOps = 4,\n BaseIv = 5,\n\n // EC Key or Oct with K\n CurveOrK = -1,\n X = -2,\n Y = -3,\n D = -4,\n}\n\n// Zod schema for CoseKey validation\nconst coseKeySchema = typedMap(\n [\n [CoseKeyParameter.KeyType, z.union([z.enum(KeyType), z.string()])],\n [\n CoseKeyParameter.KeyId,\n // NOTE: string is NOT allowed, but seems mDocs issued with v0.5 of this library\n // do include string keyIds. We need to ensure we don't break interop. For newly\n // created keys we ensure correct encoding.\n zUint8Array.or(z.string()).exactOptional(),\n ],\n [\n CoseKeyParameter.Algorithm,\n z\n .union([\n z.string({ error: 'Cose algorithm must be a string' }),\n z.number({ error: 'Cose algorithm must be a number' }),\n ])\n .exactOptional(),\n ],\n [CoseKeyParameter.KeyOps, z.array(z.union([z.enum(KeyOps), z.string()])).exactOptional()],\n [CoseKeyParameter.BaseIv, zUint8Array.exactOptional()],\n [CoseKeyParameter.CurveOrK, z.union([z.enum(Curve), zUint8Array]).exactOptional()],\n [CoseKeyParameter.X, zUint8Array.exactOptional()],\n [CoseKeyParameter.Y, zUint8Array.exactOptional()],\n [CoseKeyParameter.D, zUint8Array.exactOptional()],\n ] as const,\n { keyLabels: CoseKeyParameter }\n)\n\n// Infer structure type from Zod schema\nexport type CoseKeyDecodedStructure = z.output<typeof coseKeySchema>\nexport type CoseKeyEncodedStructure = z.input<typeof coseKeySchema>\n\n// Manual options type (user-facing API)\nexport type CoseKeyOptions = {\n keyType: KeyType | string\n keyId?: string\n algorithm?: string | number\n keyOps?: Array<KeyOps | string>\n baseIv?: Uint8Array\n\n curve?: Curve\n x?: Uint8Array\n y?: Uint8Array\n\n d?: Uint8Array\n\n k?: Uint8Array\n}\n\nexport class CoseKey extends CborStructure<CoseKeyEncodedStructure, CoseKeyDecodedStructure> {\n public static override get encodingSchema() {\n return coseKeySchema\n }\n\n public get keyType() {\n return this.structure.get(CoseKeyParameter.KeyType)\n }\n\n public get keyId() {\n const keyId = this.structure.get(CoseKeyParameter.KeyId)\n return keyId instanceof Uint8Array ? bytesToString(keyId) : keyId\n }\n\n public get algorithm() {\n return this.structure.get(CoseKeyParameter.Algorithm) as SignatureAlgorithm | MacAlgorithm | undefined\n }\n\n public get keyOps() {\n return this.structure.get(CoseKeyParameter.KeyOps)\n }\n\n public get baseIv() {\n return this.structure.get(CoseKeyParameter.BaseIv)\n }\n\n public get curve() {\n if (this.keyType === KeyType.Ec || this.keyType === KeyType.Okp) {\n // Casting is needed, as it can be both Curve or K\n return this.structure.get(CoseKeyParameter.CurveOrK) as Curve | undefined\n }\n\n return undefined\n }\n\n public get x() {\n return this.structure.get(CoseKeyParameter.X)\n }\n\n public get y() {\n return this.structure.get(CoseKeyParameter.Y)\n }\n\n public get d() {\n return this.structure.get(CoseKeyParameter.D)\n }\n\n public get k() {\n if (this.keyType === KeyType.Oct) {\n return this.structure.get(CoseKeyParameter.CurveOrK) as Uint8Array | undefined\n }\n return undefined\n }\n\n public static create(options: CoseKeyOptions) {\n const map: CoseKeyDecodedStructure = new TypedMap([[CoseKeyParameter.KeyType, options.keyType]])\n\n if (options.keyId !== undefined) {\n map.set(CoseKeyParameter.KeyId, stringToBytes(options.keyId))\n }\n\n if (options.algorithm !== undefined) {\n map.set(CoseKeyParameter.Algorithm, options.algorithm)\n }\n\n if (options.keyOps !== undefined) {\n map.set(CoseKeyParameter.KeyOps, options.keyOps)\n }\n\n if (options.baseIv !== undefined) {\n map.set(CoseKeyParameter.BaseIv, options.baseIv)\n }\n\n if (options.curve !== undefined) {\n map.set(CoseKeyParameter.CurveOrK, options.curve)\n }\n\n if (options.x !== undefined) {\n map.set(CoseKeyParameter.X, options.x)\n }\n\n if (options.y !== undefined) {\n map.set(CoseKeyParameter.Y, options.y)\n }\n\n if (options.d !== undefined) {\n map.set(CoseKeyParameter.D, options.d)\n }\n\n if (options.k !== undefined) {\n map.set(CoseKeyParameter.CurveOrK, options.k)\n }\n\n // biome-ignore lint/complexity/noThisInStatic: this.fromDecodedStructure is intentional for subclass support\n return this.fromDecodedStructure(map)\n }\n\n // TODO: add jwk zod schema\n public static fromJwk(jwk: Record<string, unknown>) {\n if (!('kty' in jwk)) {\n throw new CoseInvalidValueForKtyError('JWK does not contain required kty value')\n }\n\n const options = Object.entries(jwk).reduce((prev, [key, value]) => {\n const mappedKey = jwkCoseOptionsMap[key] ?? key\n\n const mapFunction = jwkToCoseKey[key as keyof typeof jwkToCoseKey]\n const convertedValue = mapFunction ? mapFunction(value) : value\n\n // Only include if value is not undefined\n if (convertedValue !== undefined) {\n // biome-ignore lint/performance/noAccumulatingSpread: time-complexity is not relevant here\n return { ...prev, [mappedKey]: convertedValue }\n }\n\n return prev\n }, {} as CoseKeyOptions)\n\n // biome-ignore lint/complexity/noThisInStatic: this.create is intentional for subclass support\n return this.create(options)\n }\n\n public get publicKey() {\n if (this.keyType !== KeyType.Ec && this.keyType !== KeyType.Okp) {\n throw new CoseInvalidKtyForRawError()\n }\n\n if (!this.x) {\n throw new CoseXNotDefinedError()\n }\n\n if (this.keyType === KeyType.Okp) {\n return this.x\n }\n\n if (!this.y) {\n throw new CoseYNotDefinedError()\n }\n\n return concatBytes(Uint8Array.from([0x04]), this.x, this.y)\n }\n\n /**\n *\n * @returns the `d` value for `ec` and `okp` key types\n * @returns the `k` value for `oct` key types\n *\n */\n public get privateKey() {\n if (this.keyType === KeyType.Ec || this.keyType === KeyType.Okp) {\n if (!this.d) {\n throw new CoseDNotDefinedError()\n }\n\n return this.d\n }\n\n if (this.keyType === KeyType.Oct) {\n if (!this.k) {\n throw new CoseKNotDefinedError()\n }\n\n return this.k\n }\n\n throw new CoseKeyTypeNotSupportedForPrivateKeyExtractionError()\n }\n\n public get jwk(): Record<string, unknown> {\n // Convert CoseKey properties to JWK format\n const options: CoseKeyOptions = {\n keyType: this.keyType,\n keyId: this.keyId,\n algorithm: this.algorithm,\n keyOps: this.keyOps,\n baseIv: this.baseIv,\n curve: this.curve,\n x: this.x,\n y: this.y,\n d: this.d,\n k: this.k,\n }\n\n return Object.entries(options).reduce(\n (prev, [key, value]) => ({\n // biome-ignore lint/performance/noAccumulatingSpread: time-complexity is not relevant here\n ...prev,\n [coseOptionsJwkMap[key] ?? key]:\n typeof coseKeyToJwkClaim[key as keyof typeof coseKeyToJwkClaim] === 'function'\n ? // @ts-ignore\n coseKeyToJwkClaim[key as keyof typeof coseKeyToJwkClaim](value)\n : undefined,\n }),\n {}\n )\n }\n}\n","import { z } from 'zod'\nimport {\n type AnyCborStructure,\n addExtension,\n CborStructure,\n type CborStructureStaticThis,\n cborDecode,\n cborEncode,\n type EncodedStructureType,\n} from '../cbor'\nimport { zUint8Array } from '../utils/zod'\nimport { CoseInvalidAlgorithmError, CosePayloadMustBeDefinedError } from './error'\nimport { MacAlgorithm, RegisteredCwtHeaderClaimKey } from './headers/defaults'\nimport {\n type ProtectedHeaderOptions,\n ProtectedHeaders,\n type ProtectedHeadersEncodedStructure,\n} from './headers/protected-headers'\nimport {\n type UnprotectedHeaderOptions,\n UnprotectedHeaders,\n type UnprotectedHeadersStructure,\n} from './headers/unprotected-headers'\nimport { CoseKey } from './key'\nimport { coseKeyToJwkClaim } from './key/jwk'\n\nexport const mac0EncodedSchema = z.tuple([\n zUint8Array,\n z.map(z.unknown(), z.unknown()),\n zUint8Array.nullable(),\n zUint8Array,\n])\n\nexport const mac0DecodedSchema = z.object({\n protectedHeaders: z.instanceof(ProtectedHeaders),\n unprotectedHeaders: z.instanceof(UnprotectedHeaders),\n payload: zUint8Array.nullable(),\n tag: zUint8Array,\n})\n\nexport type Mac0EncodedStructure = z.infer<typeof mac0EncodedSchema>\nexport type Mac0DecodedStructure = z.infer<typeof mac0DecodedSchema>\n\nexport type Mac0Context = {\n authenticate: (options: {\n toBeAuthenticated: Uint8Array\n key: CoseKey | Uint8Array\n algorithm?: MacAlgorithm\n }) => Promise<Uint8Array>\n verify: (options: {\n toBeAuthenticated: Uint8Array\n tag: Uint8Array\n key: CoseKey | Uint8Array\n algorithm?: MacAlgorithm\n }) => Promise<boolean>\n}\n\nexport type Mac0Options = {\n protectedHeaders?: ProtectedHeaders | ProtectedHeaderOptions['protectedHeaders']\n unprotectedHeaders?: UnprotectedHeaders | UnprotectedHeaderOptions['unprotectedHeaders']\n\n /**\n * The embedded payload. Pass `null` to explicitly signal a detached payload\n * (the encoded structure will contain null, and you must supply the payload\n * via `detachedPayload` when calling `authenticate()` / `toBeAuthenticated()`).\n */\n payload: Uint8Array | null\n\n tag?: Uint8Array\n}\n\nexport class Mac0 extends CborStructure<Mac0EncodedStructure, Mac0DecodedStructure> {\n public static tag = 17\n protected override _tag = Mac0.tag\n\n public static override get encodingSchema() {\n return z.codec(mac0EncodedSchema, mac0DecodedSchema, {\n encode: ({ protectedHeaders, unprotectedHeaders, payload, tag }) => {\n if (tag.length === 0) {\n throw new Error('Tag has not been set. Required for encoding the mac0 structure')\n }\n return [\n protectedHeaders.encodedStructure,\n unprotectedHeaders.encodedStructure,\n payload,\n tag,\n ] satisfies Mac0EncodedStructure\n },\n decode: ([protectedHeadersBytes, unprotectedHeadersMap, payload, tag]) => ({\n protectedHeaders: ProtectedHeaders.fromEncodedStructure(\n protectedHeadersBytes as ProtectedHeadersEncodedStructure\n ),\n unprotectedHeaders: UnprotectedHeaders.fromEncodedStructure(\n unprotectedHeadersMap as UnprotectedHeadersStructure\n ),\n payload,\n tag,\n }),\n })\n }\n\n public get protectedHeaders() {\n return this.structure.protectedHeaders\n }\n\n public get unprotectedHeaders() {\n return this.structure.unprotectedHeaders\n }\n\n public get payload() {\n return this.structure.payload\n }\n\n public get tag() {\n return this.structure.tag\n }\n\n /**\n * Returns the MAC_Structure bytes that are authenticated/verified.\n *\n * @param options.detachedPayload - The detached payload to use. Must be provided when\n * the Mac0 was created with a detached payload (i.e. `payload` field is null).\n * Cannot be provided when the Mac0 already contains an embedded payload.\n * @param options.externalAad - Externally supplied data covered by the authentication tag. It is\n * not part of the COSE structure, so it has to be provided identically wherever the\n * MAC_Structure is built: `authenticate()`, `verifyAuthenticationCode()` and here.\n */\n public toBeAuthenticated(options?: { detachedPayload?: Uint8Array; externalAad?: Uint8Array }): Uint8Array {\n const embeddedPayload = this.payload\n const detachedPayload = options?.detachedPayload\n\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Mac0 already contains an embedded payload')\n }\n\n const payload = embeddedPayload ?? detachedPayload\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n return Mac0.toBeAuthenticated({\n payload,\n protectedHeaders: this.protectedHeaders,\n externalAad: options?.externalAad,\n })\n }\n\n /**\n * Decodes CBOR bytes into a Mac0 instance.\n * Uses the encodingSchema's decode() method to validate and transform the decoded data.\n */\n public static decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n const rawStructure = cborDecode(bytes)\n\n // May feel weird, but using new this makes TypeScript understand we may return a subclass\n return new this(\n // NOTE: If decoded with Mac0 tag, the cbor decoder already transforms to the class instances\n // In that case we create new instance based on the decoded structure, to ensure we create the\n // instance based on this (and ensure extended classes work)\n // biome-ignore lint/complexity/noThisInStatic: this check is intentional for subclass support\n rawStructure instanceof Mac0 && rawStructure.constructor === this\n ? rawStructure.decodedStructure\n : // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\n this.fromEncodedStructure(\n (rawStructure instanceof Mac0 ? rawStructure.encodedStructure : rawStructure) as EncodedStructureType<T>\n ).decodedStructure\n ) as unknown as T\n }\n\n public static toBeAuthenticated(options: {\n payload: Uint8Array\n protectedHeaders: ProtectedHeaders\n externalAad?: Uint8Array\n }) {\n const toBeAuthenticated = ['MAC0', options.protectedHeaders.encodedStructure]\n if (options.externalAad) toBeAuthenticated.push(options.externalAad)\n toBeAuthenticated.push(options.payload)\n\n return cborEncode(toBeAuthenticated)\n }\n\n public get algorithm(): MacAlgorithm | undefined {\n const algorithm = this.protectedHeaders.headers?.get(RegisteredCwtHeaderClaimKey.Algorithm) as\n | MacAlgorithm\n | undefined\n if (algorithm && !Object.values(MacAlgorithm).includes(algorithm)) {\n throw new CoseInvalidAlgorithmError()\n }\n\n return algorithm\n }\n\n public get jwaAlgorithm(): keyof typeof MacAlgorithm {\n const alg = this.algorithm\n\n const jwaAlg = coseKeyToJwkClaim.algorithm(alg)\n if (!jwaAlg) {\n throw new CoseInvalidAlgorithmError(`Cose algorithm ${alg} does not have a corresponding JWA alg`)\n }\n\n return jwaAlg\n }\n\n public static create(options: Mac0Options): Mac0 {\n const protectedHeaders =\n options.protectedHeaders instanceof ProtectedHeaders\n ? options.protectedHeaders\n : ProtectedHeaders.create({ protectedHeaders: options.protectedHeaders })\n\n const unprotectedHeaders =\n options.unprotectedHeaders instanceof UnprotectedHeaders\n ? options.unprotectedHeaders\n : UnprotectedHeaders.create({ unprotectedHeaders: options.unprotectedHeaders })\n\n const mac0 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n tag: options.tag ?? new Uint8Array(),\n })\n\n return mac0\n }\n\n public async authenticate(\n options: {\n key: CoseKey | Uint8Array\n detachedPayload?: Uint8Array\n algorithm?: MacAlgorithm\n externalAad?: Uint8Array\n },\n ctx: Pick<Mac0Context, 'authenticate'>\n ) {\n const embeddedPayload = this.payload\n const { detachedPayload } = options\n\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Mac0 already contains an embedded payload')\n }\n\n const payload = embeddedPayload ?? detachedPayload\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n // TODO: do we want to check whether key.algorithm and options.algorithm exist?\n const macAlgorithm = (options.key instanceof CoseKey ? options.key.algorithm : options.algorithm) as\n | MacAlgorithm\n | undefined\n\n if (!macAlgorithm) {\n throw new CoseInvalidAlgorithmError(\n 'Could not establish mac algorithm. Either provide it in the options directly, or provide it in the signingKey'\n )\n }\n\n if (!Object.values(MacAlgorithm).includes(macAlgorithm as MacAlgorithm)) {\n throw new CoseInvalidAlgorithmError('Invalid mac algorithm.')\n }\n\n this.structure.tag = await ctx.authenticate({\n toBeAuthenticated: Mac0.toBeAuthenticated({\n payload,\n protectedHeaders: this.protectedHeaders,\n externalAad: options.externalAad,\n }),\n algorithm: macAlgorithm,\n key: options.key,\n })\n return this\n }\n\n public async verifyAuthenticationCode(\n { key, detachedPayload, externalAad }: { key: CoseKey; detachedPayload?: Uint8Array; externalAad?: Uint8Array },\n ctx: Pick<Mac0Context, 'verify'>\n ) {\n const embeddedPayload = this.payload\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Mac0 already contains an embedded payload')\n }\n\n return await ctx.verify({\n key,\n tag: this.tag,\n toBeAuthenticated: this.toBeAuthenticated({ detachedPayload, externalAad }),\n algorithm: this.algorithm,\n })\n }\n}\n\naddExtension({\n Class: Mac0,\n tag: Mac0.tag,\n encode(instance: Mac0, encodeFn: (obj: unknown) => Uint8Array) {\n return encodeFn(instance)\n },\n decode: (encoded) => Mac0.fromEncodedStructure(encoded as Mac0EncodedStructure),\n})\n","import z from 'zod'\nimport {\n type AnyCborStructure,\n CborStructure,\n type CborStructureStaticThis,\n cborDecode,\n cborEncode,\n type EncodedStructureType,\n} from '../cbor'\nimport { addExtension } from '../cbor/cbor-x'\nimport { zUint8Array } from '../utils/zod'\nimport { CoseCertificateNotFoundError, CoseInvalidAlgorithmError, CosePayloadMustBeDefinedError } from './error'\nimport {\n type ProtectedHeaderOptions,\n ProtectedHeaders,\n protectedHeadersEncodedStructure,\n RegisteredCwtHeaderClaimKey,\n SignatureAlgorithm,\n type UnprotectedHeaderOptions,\n UnprotectedHeaders,\n unprotectedHeadersStructure,\n} from './headers'\nimport { type CoseKey, Curve, coseKeyToJwkClaim, KeyType } from './key'\n\nexport const sign1EncodedSchema = z.tuple([\n // protected headers\n protectedHeadersEncodedStructure,\n // unprotected headers\n unprotectedHeadersStructure,\n // payload\n zUint8Array.nullable(),\n // signature\n zUint8Array,\n])\n\nexport const sign1DecodedSchema = z.object({\n protectedHeaders: z.instanceof(ProtectedHeaders),\n unprotectedHeaders: z.instanceof(UnprotectedHeaders),\n payload: sign1EncodedSchema.def.items[2],\n signature: sign1EncodedSchema.def.items[3],\n})\n\nexport type Sign1EncodedStructure = z.infer<typeof sign1EncodedSchema>\nexport type Sign1DecodedStructure = z.infer<typeof sign1DecodedSchema>\n\nconst ecdsaCurves = [Curve['P-256'], Curve['P-384'], Curve['P-521']]\nconst eddsaCurves = [Curve.Ed25519, Curve.Ed448]\n\n/**\n * The key type and curves each signature algorithm accepts: RFC 9053 § 2.1 and § 2.2 for the\n * polymorphic ECDSA and EdDSA algorithms, and RFC 9864 § 2.1 and § 2.2 for the fully-specified\n * ones, which fix the curve. RSA keys have no `KeyType`, so the RSA algorithms are not listed.\n */\nconst signatureAlgorithmKeys = new Map<SignatureAlgorithm, { keyType: KeyType.Ec | KeyType.Okp; curves: Curve[] }>([\n [SignatureAlgorithm.ES256, { keyType: KeyType.Ec, curves: ecdsaCurves }],\n [SignatureAlgorithm.ES384, { keyType: KeyType.Ec, curves: ecdsaCurves }],\n [SignatureAlgorithm.ES512, { keyType: KeyType.Ec, curves: ecdsaCurves }],\n [SignatureAlgorithm.ESP256, { keyType: KeyType.Ec, curves: [Curve['P-256']] }],\n [SignatureAlgorithm.ESP384, { keyType: KeyType.Ec, curves: [Curve['P-384']] }],\n [SignatureAlgorithm.ESP512, { keyType: KeyType.Ec, curves: [Curve['P-521']] }],\n [SignatureAlgorithm.EdDSA, { keyType: KeyType.Okp, curves: eddsaCurves }],\n [SignatureAlgorithm.Ed25519, { keyType: KeyType.Okp, curves: [Curve.Ed25519] }],\n [SignatureAlgorithm.Ed448, { keyType: KeyType.Okp, curves: [Curve.Ed448] }],\n])\n\nconst keyTypeNames = { [KeyType.Ec]: 'EC2', [KeyType.Okp]: 'OKP' }\n\n/**\n * Rejects a key the algorithm is not defined for, rather than leaving it to the context, which may\n * pick the curve from the key alone. Only the key type and curve are compared: a key is valid for\n * every algorithm that accepts them, whatever its own `alg`.\n */\nconst assertKeyMatchesAlgorithm = (key: CoseKey, algorithm?: SignatureAlgorithm) => {\n if (algorithm === undefined) return\n const requirement = signatureAlgorithmKeys.get(algorithm)\n if (!requirement) return\n\n const { keyType, curves } = requirement\n if (key.keyType !== keyType || key.curve === undefined || !curves.includes(key.curve)) {\n throw new CoseInvalidAlgorithmError(\n `Algorithm ${SignatureAlgorithm[algorithm]} requires an ${keyTypeNames[keyType]} key on curve ${curves.map((curve) => Curve[curve]).join(' or ')}`\n )\n }\n}\n\nexport type Sign1Context = {\n sign: (options: { toBeSigned: Uint8Array; key: CoseKey; algorithm: SignatureAlgorithm }) => Promise<Uint8Array>\n verify: (options: {\n toBeVerified: Uint8Array\n signature: Uint8Array\n key: CoseKey\n algorithm?: SignatureAlgorithm\n }) => Promise<boolean>\n}\n\nexport type Sign1Options = {\n protectedHeaders?: ProtectedHeaders | ProtectedHeaderOptions['protectedHeaders']\n unprotectedHeaders?: UnprotectedHeaders | UnprotectedHeaderOptions['unprotectedHeaders']\n\n /**\n * The embedded payload. Pass `null` to explicitly signal a detached payload\n * (the encoded structure will contain null, and you must supply the payload\n * via `detachedPayload` when calling `sign()` / `verifySignature()` / `toBeSigned()`).\n */\n payload: Uint8Array | null\n\n signature?: Uint8Array\n}\n\nexport class Sign1 extends CborStructure<Sign1EncodedStructure, Sign1DecodedStructure> {\n public static tag = 18\n protected override _tag = Sign1.tag\n\n public static override get encodingSchema() {\n return z.codec(sign1EncodedSchema, sign1DecodedSchema, {\n encode: (decoded) => {\n if (decoded.signature.length === 0) {\n throw new Error('Signature has not been set. Required for encoding the sign1 structure')\n }\n\n return [\n decoded.protectedHeaders.encodedStructure,\n decoded.unprotectedHeaders.encodedStructure,\n decoded.payload,\n decoded.signature,\n ] satisfies Sign1EncodedStructure\n },\n decode: ([protectedHeaders, unprotected, payload, signature]) => ({\n protectedHeaders: ProtectedHeaders.fromEncodedStructure(protectedHeaders),\n unprotectedHeaders: UnprotectedHeaders.fromEncodedStructure(unprotected),\n payload,\n signature,\n }),\n })\n }\n\n public get protectedHeaders() {\n return this.structure.protectedHeaders\n }\n\n public get unprotectedHeaders() {\n return this.structure.unprotectedHeaders\n }\n\n public get payload() {\n return this.structure.payload\n }\n\n public get signature() {\n return this.structure.signature\n }\n\n public get certificateChain() {\n return this.x5chain ?? []\n }\n\n public get certificate() {\n const [certificate] = this.certificateChain\n\n if (!certificate) {\n throw new CoseCertificateNotFoundError()\n }\n\n return certificate\n }\n\n /**\n * Returns the Sig_Structure bytes that are signed/verified.\n *\n * @param options.detachedPayload - The detached payload to use. Must be provided when\n * the Sign1 was created with a detached payload (i.e. `payload` field is null).\n * Cannot be provided when the Sign1 already contains an embedded payload.\n * @param options.externalAad - Externally supplied data covered by the signature. It is not part\n * of the COSE structure, so it has to be provided identically wherever the Sig_Structure is\n * built: `sign()`, `verifySignature()` and here.\n */\n public toBeSigned(options?: { detachedPayload?: Uint8Array; externalAad?: Uint8Array }): Uint8Array {\n const embeddedPayload = this.payload\n const detachedPayload = options?.detachedPayload\n\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Sign1 already contains an embedded payload')\n }\n\n const payload = embeddedPayload ?? detachedPayload\n\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n return Sign1.toBeSigned({\n payload,\n protectedHeaders: this.protectedHeaders,\n externalAad: options?.externalAad,\n })\n }\n\n /**\n * Decodes CBOR bytes into a Sign1 instance.\n * Uses the encodingSchema's decode() method to validate and transform the decoded data.\n */\n public static decode<T extends AnyCborStructure>(this: CborStructureStaticThis<T>, bytes: Uint8Array): T {\n const rawStructure = cborDecode(bytes)\n\n // May feel weird, but using new this makes TypeScript understand we may return a subclass\n return new this(\n // NOTE: If decoded with Sign1 tag, the cbor decoder already transforms to the class instances\n // In that case we create new instance based on the decoded structure, to ensure we create the\n // instance based on this (and ensure extended classes work)\n // biome-ignore lint/complexity/noThisInStatic: this check is intentional for subclass support\n rawStructure instanceof Sign1 && rawStructure.constructor === this\n ? rawStructure.decodedStructure\n : // biome-ignore lint/complexity/noThisInStatic: this.fromEncodedStructure is intentional for subclass support\n this.fromEncodedStructure(\n (rawStructure instanceof Sign1 ? rawStructure.encodedStructure : rawStructure) as EncodedStructureType<T>\n ).decodedStructure\n ) as unknown as T\n }\n\n public static toBeSigned(options: {\n payload: Uint8Array\n protectedHeaders: ProtectedHeaders\n externalAad?: Uint8Array\n }) {\n const toBeSigned = [\n 'Signature1',\n options.protectedHeaders.encodedStructure,\n options.externalAad ?? new Uint8Array(),\n options.payload,\n ]\n\n return cborEncode(toBeSigned)\n }\n\n public get algorithm(): SignatureAlgorithm | undefined {\n const algorithm = this.protectedHeaders.headers?.get(RegisteredCwtHeaderClaimKey.Algorithm) as\n | SignatureAlgorithm\n | undefined\n if (algorithm && !Object.values(SignatureAlgorithm).includes(algorithm)) {\n throw new CoseInvalidAlgorithmError()\n }\n\n return algorithm\n }\n\n public get jwaAlgorithm(): keyof typeof SignatureAlgorithm | undefined {\n const alg = this.algorithm\n if (!alg) return undefined\n\n const jwaAlg = coseKeyToJwkClaim.algorithm(alg)\n if (!jwaAlg) {\n throw new CoseInvalidAlgorithmError(`Cose algorithm ${alg} does not have a corresponding JWA alg`)\n }\n\n return jwaAlg\n }\n\n public get x5chain() {\n // TODO: typed keys for headers\n // FIXME: why are we looking at unprotected header for x5c?\n const x5chain =\n (this.protectedHeaders.headers?.get(RegisteredCwtHeaderClaimKey.X5Chain) as\n | Uint8Array\n | Uint8Array[]\n | undefined) ??\n (this.unprotectedHeaders.headers?.get(RegisteredCwtHeaderClaimKey.X5Chain) as\n | Uint8Array\n | Uint8Array[]\n | undefined)\n\n if (!x5chain?.[0]) {\n return undefined\n }\n\n return Array.isArray(x5chain) ? x5chain : [x5chain]\n }\n\n public async verifySignature(\n { key, detachedPayload, externalAad }: { key: CoseKey; detachedPayload?: Uint8Array; externalAad?: Uint8Array },\n ctx: Pick<Sign1Context, 'verify'>\n ) {\n const embeddedPayload = this.payload\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Sign1 already contains an embedded payload')\n }\n\n const algorithm = this.algorithm\n assertKeyMatchesAlgorithm(key, algorithm)\n\n return await ctx.verify({\n toBeVerified: this.toBeSigned({ detachedPayload, externalAad }),\n signature: this.signature,\n key,\n algorithm,\n })\n }\n\n public static create(options: Sign1Options) {\n const protectedHeaders =\n options.protectedHeaders instanceof ProtectedHeaders\n ? options.protectedHeaders\n : ProtectedHeaders.create({ protectedHeaders: options.protectedHeaders })\n\n const unprotectedHeaders =\n options.unprotectedHeaders instanceof UnprotectedHeaders\n ? options.unprotectedHeaders\n : UnprotectedHeaders.create({ unprotectedHeaders: options.unprotectedHeaders })\n\n const sign1 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n signature: options.signature ?? new Uint8Array(),\n })\n\n return sign1\n }\n\n public async sign(\n options: {\n externalAad?: Uint8Array\n signingKey: CoseKey\n algorithm?: SignatureAlgorithm\n detachedPayload?: Uint8Array\n },\n ctx: Pick<Sign1Context, 'sign'>\n ) {\n const embeddedPayload = this.payload\n const { detachedPayload } = options\n\n if (embeddedPayload && detachedPayload) {\n throw new Error('Cannot provide detachedPayload when the Sign1 already contains an embedded payload')\n }\n\n const payload = embeddedPayload ?? detachedPayload\n if (!payload) {\n throw new CosePayloadMustBeDefinedError()\n }\n\n const signatureAlgorithm = options.algorithm ?? options.signingKey.algorithm\n\n if (!signatureAlgorithm) {\n throw new CoseInvalidAlgorithmError(\n 'Could not establish signature algorithm. Either provide it in the options directly, or provide it in the signingKey'\n )\n }\n\n if (!Object.values(SignatureAlgorithm).includes(signatureAlgorithm as SignatureAlgorithm)) {\n throw new CoseInvalidAlgorithmError('algorithm provided in the options or key is not a valid signing algorithm')\n }\n\n assertKeyMatchesAlgorithm(options.signingKey, signatureAlgorithm as SignatureAlgorithm)\n\n this.structure.signature = await ctx.sign({\n toBeSigned: Sign1.toBeSigned({\n payload,\n protectedHeaders: this.protectedHeaders,\n externalAad: options.externalAad,\n }),\n key: options.signingKey,\n algorithm: signatureAlgorithm as SignatureAlgorithm,\n })\n\n return this\n }\n}\n\naddExtension({\n Class: Sign1,\n tag: Sign1.tag,\n encode(instance: Sign1, encodeFn: (obj: unknown) => Uint8Array) {\n return encodeFn(instance)\n },\n decode: (encoded) => Sign1.fromEncodedStructure(encoded as Sign1EncodedStructure),\n})\n","import type { AnyCborStructure, EncodedStructureType } from '../cbor'\nimport { cborDecode, describeCborValue } from '../cbor'\nimport { Tag } from '../cbor/cbor-x'\nimport type { AnyCwtPayload, CwtPayload } from './claims/cwt-payload'\nimport {\n CoseInvalidSignatureError,\n CosePayloadInvalidStructureError,\n CwtDetachedPayloadError,\n CwtMissingVerifyContextError,\n CwtNotSignedError,\n CwtPayloadDecodeError,\n} from './error'\nimport {\n type ProtectedHeaderOptions,\n ProtectedHeaders,\n RegisteredCwtHeaderClaimKey,\n type SignatureAlgorithm,\n type UnprotectedHeaderOptions,\n UnprotectedHeaders,\n} from './headers'\nimport type { CoseKey } from './key'\nimport { Mac0, type Mac0Context } from './mac0'\nimport { Sign1, type Sign1Context } from './sign1'\n\n/**\n * The CWT CBOR tag, defined in RFC 8392. It wraps the COSE structure rather than replacing it,\n * so a token tagged with it must be unwrapped before the COSE structure can be decoded.\n */\nconst CWT_TAG = 61\n\n/**\n * A raw header map is only accepted for a CWT that uses the default header structures. A CWT type\n * with its own header class has to be given an instance of that class, so that the map is validated\n * against the class's schema instead of the registered COSE header claims.\n */\ntype RawHeadersFor<Headers, Raw> = ProtectedHeaders extends Headers\n ? Raw\n : UnprotectedHeaders extends Headers\n ? Raw\n : never\n\nexport type CwtOptions<\n Payload extends AnyCwtPayload = CwtPayload,\n ProtectedHeadersStructure extends AnyProtectedHeaders = ProtectedHeaders,\n UnprotectedHeadersStructure extends AnyUnprotectedHeaders = UnprotectedHeaders,\n> = {\n protectedHeaders?:\n | ProtectedHeadersStructure\n | RawHeadersFor<ProtectedHeadersStructure, ProtectedHeaderOptions['protectedHeaders']>\n unprotectedHeaders?:\n | UnprotectedHeadersStructure\n | RawHeadersFor<UnprotectedHeadersStructure, UnprotectedHeaderOptions['unprotectedHeaders']>\n\n /** The CWT claims set. */\n payload: Payload\n\n /**\n * The COSE_Sign1 signature over the payload. Set for a signed CWT, and mutually exclusive with\n * {@link tag} — a CWT is one or the other.\n */\n signature?: Uint8Array\n\n /**\n * The COSE_Mac0 authentication tag over the payload. Set for a MACed CWT, and mutually exclusive\n * with {@link signature}.\n */\n tag?: Uint8Array\n\n /**\n * The payload bytes exactly as they appeared in the COSE message. Set when decoding a token, so\n * that verification can use them directly rather than re-encoding the decoded payload. Do not\n * pass this when constructing a CWT yourself.\n *\n * @see {@link Cwt.payloadBytes}\n */\n originalPayloadBytes?: Uint8Array\n}\n\n/**\n * The verification context {@link Cwt.verify} needs. Both are optional, so a caller that only deals\n * with one of the two COSE structures passes only that one, and a CWT carried in the other is\n * rejected rather than verified with the wrong context.\n */\nexport type CwtVerifyContext = {\n /** Verifies the signature of a CWT carried in a COSE_Sign1. */\n sign1?: Pick<Sign1Context, 'verify'>\n\n /** Verifies the authentication tag of a CWT carried in a COSE_Mac0. */\n mac0?: Pick<Mac0Context, 'verify'>\n}\n\n/**\n * The options the payload of `Cwt` takes for claim verification. Reading them off the payload class\n * is what lets a CWT type require its own options — a status list CWT its `uri`, say — on the `Cwt`\n * methods that forward to it.\n */\nexport type CwtClaimsOptionsFor<Payload extends AnyCwtPayload> = NonNullable<Parameters<Payload['verifyClaims']>[0]>\n\n/** The options {@link Cwt.verify} takes: the key, the claim options of its payload, and the AAD. */\nexport type CwtVerifyOptions<Payload extends AnyCwtPayload> = {\n key: CoseKey\n\n /**\n * Externally supplied data covered by the signature or authentication tag. It is not carried in\n * the token, so it has to be the same value the issuer signed with.\n */\n externalAad?: Uint8Array\n} & CwtClaimsOptionsFor<Payload>\n\n// biome-ignore lint/suspicious/noExplicitAny: intentionally unconstrained, used as a generic bound\nexport type AnyProtectedHeaders = ProtectedHeaders<any>\n// biome-ignore lint/suspicious/noExplicitAny: intentionally unconstrained, used as a generic bound\nexport type AnyUnprotectedHeaders = UnprotectedHeaders<any>\n\n// biome-ignore lint/suspicious/noExplicitAny: intentionally unconstrained, used as a generic bound\nexport type AnyCwt = Cwt<any, any, any>\n\n// biome-ignore lint/suspicious/noExplicitAny: matching any header structure\nexport type CwtPayloadType<T> = T extends Cwt<infer Payload, any, any> ? Payload : never\n// biome-ignore lint/suspicious/noExplicitAny: matching any payload/header structure\nexport type CwtProtectedHeadersType<T> = T extends Cwt<any, infer Headers, any> ? Headers : never\n// biome-ignore lint/suspicious/noExplicitAny: matching any payload/header structure\nexport type CwtUnprotectedHeadersType<T> = T extends Cwt<any, any, infer Headers> ? Headers : never\n\n/**\n * The static side of a `CborStructure` subclass, reduced to what decoding a CWT needs: turning an\n * encoded structure into a validated instance. Kept structural rather than `typeof SomeClass` so\n * that any subclass is accepted.\n */\nexport type CwtStructureClass<Structure extends AnyCborStructure> = {\n fromEncodedStructure(encodedStructure: EncodedStructureType<Structure>): Structure\n}\n\n/**\n * The structure classes a token is decoded into. Passed to {@link Cwt.fromToken}, which is the only\n * place that has to turn bytes back into structures, rather than declared as statics on the class:\n * a CWT type that wants to hide them overrides `fromToken` and supplies them there.\n */\nexport type CwtStructures<T extends AnyCwt> = {\n payload: CwtStructureClass<CwtPayloadType<T>>\n protectedHeaders?: CwtStructureClass<CwtProtectedHeadersType<T>>\n unprotectedHeaders?: CwtStructureClass<CwtUnprotectedHeadersType<T>>\n}\n\n/**\n * The static side of a `Cwt` subclass, so `fromToken` can construct (and type) the subclass it was\n * called on rather than the base class.\n */\nexport type CwtStaticThis<T extends AnyCwt> = {\n new (options: CwtOptions<CwtPayloadType<T>, CwtProtectedHeadersType<T>, CwtUnprotectedHeadersType<T>>): T\n}\n\n/**\n * A CBOR Web Token (RFC 8392): a COSE_Sign1 or COSE_Mac0 whose payload is a CWT claims set.\n *\n * A CWT type is expressed by the structures it is made of: a {@link CwtPayload} subclass for the\n * claims set, and a {@link ProtectedHeaders} / {@link UnprotectedHeaders} subclass for a header\n * bucket whose labels it adds to or narrows. Each of those validates itself through its own\n * `encodingSchema`, so `Cwt` holds no schemas and needs no per-type statics.\n *\n * The classes are named where a token is turned back into structures, which is `fromToken`:\n *\n * ```ts\n * const cwt = Cwt.fromToken(token, {\n * payload: StatusListCwtPayload,\n * protectedHeaders: StatusListCwtProtectedHeaders,\n * })\n *\n * cwt.payload.statusList // typed\n * ```\n *\n * A CWT type that carries extra logic subclasses `Cwt` and overrides `fromToken` to supply them, so\n * callers do not repeat the classes:\n *\n * ```ts\n * class StatusListCwt extends Cwt<StatusListCwtPayload, StatusListCwtProtectedHeaders> {\n * public static override fromToken(token: Uint8Array) {\n * return super.fromToken(token, {\n * payload: StatusListCwtPayload,\n * protectedHeaders: StatusListCwtProtectedHeaders,\n * })\n * }\n * }\n * ```\n *\n * @template Payload - The claims set structure for this CWT type.\n * @template ProtectedHeadersStructure - The protected header structure for this CWT type.\n * @template UnprotectedHeadersStructure - The unprotected header structure for this CWT type.\n */\nexport class Cwt<\n Payload extends AnyCwtPayload = CwtPayload,\n ProtectedHeadersStructure extends AnyProtectedHeaders = ProtectedHeaders,\n UnprotectedHeadersStructure extends AnyUnprotectedHeaders = UnprotectedHeaders,\n> {\n #payload: Payload\n\n /**\n * The claims set of this CWT.\n *\n * Assignable, and assigning drops the retained {@link originalPayloadBytes}, so the new claims set\n * is what gets signed or verified. Mutating the claims set in place cannot be seen from here, so\n * call {@link markPayloadModified} after doing so — the mutation helpers a CWT type exposes, such\n * as `StatusListCwt.updateStatusList`, already do.\n */\n public get payload(): Payload {\n return this.#payload\n }\n\n public set payload(payload: Payload) {\n this.#payload = payload\n this.markPayloadModified()\n }\n\n public protectedHeaders: ProtectedHeadersStructure\n public unprotectedHeaders: UnprotectedHeadersStructure\n\n /**\n * The COSE_Sign1 signature over the payload, for a signed CWT.\n *\n * Kept apart from {@link tag} rather than as one 'signature or tag' value, because which of the\n * two a CWT carries is what says whether it is a COSE_Sign1 or a COSE_Mac0 — a distinction the\n * encoded structure does not carry, and that {@link verify} needs.\n */\n public signature?: Uint8Array\n\n /** The COSE_Mac0 authentication tag over the payload, for a MACed CWT. See {@link signature}. */\n public tag?: Uint8Array\n\n /**\n * The payload bytes as received in the COSE message, kept so that verification can use them\n * directly. RFC 9052 puts the payload into `Sig_structure`/`MAC_structure` as an opaque `bstr`, so\n * what was signed is the exact bytes the issuer sent, not whatever we would encode the decoded\n * payload back into. Cleared by {@link markPayloadModified}, since the signature over it no longer\n * means anything once the payload changed.\n *\n * @see https://datatracker.ietf.org/doc/rfc9052/#section-4.4\n * @see https://datatracker.ietf.org/doc/rfc9052/#section-6\n */\n private originalPayloadBytes?: Uint8Array\n\n public constructor(options: CwtOptions<Payload, ProtectedHeadersStructure, UnprotectedHeadersStructure>) {\n // Set the field rather than going through the setter: there is nothing to invalidate yet, and\n // `originalPayloadBytes` is assigned below.\n this.#payload = options.payload\n\n // A raw map only reaches here for a CWT using the default header structures, see `RawHeadersFor`.\n // `create` validates it, so the headers of every CWT are checked by their own schema.\n this.protectedHeaders = (\n options.protectedHeaders instanceof ProtectedHeaders\n ? options.protectedHeaders\n : ProtectedHeaders.create({ protectedHeaders: options.protectedHeaders as Map<number, unknown> | undefined })\n ) as ProtectedHeadersStructure\n this.unprotectedHeaders = (\n options.unprotectedHeaders instanceof UnprotectedHeaders\n ? options.unprotectedHeaders\n : UnprotectedHeaders.create({\n unprotectedHeaders: options.unprotectedHeaders as Map<number, unknown> | undefined,\n })\n ) as UnprotectedHeadersStructure\n\n if (options.signature && options.tag) {\n throw new CosePayloadInvalidStructureError(\n 'A CWT carries either a COSE_Sign1 signature or a COSE_Mac0 authentication tag, not both'\n )\n }\n\n this.signature = options.signature\n this.tag = options.tag\n this.originalPayloadBytes = options.originalPayloadBytes\n }\n\n public static create<T extends AnyCwt>(\n this: CwtStaticThis<T>,\n options: CwtOptions<CwtPayloadType<T>, CwtProtectedHeadersType<T>, CwtUnprotectedHeadersType<T>>\n ): T {\n return new this(options)\n }\n\n /**\n * Decodes a CWT from a tagged COSE_Sign1 (tag 18) or COSE_Mac0 (tag 17) token.\n *\n * @throws CborDecodeError if the token is not valid CBOR.\n * @throws CosePayloadInvalidStructureError if the token is valid CBOR but not a COSE_Sign1/COSE_Mac0.\n * @throws CwtDetachedPayloadError if the token carries a detached (null) payload.\n * @throws CwtPayloadDecodeError if the payload is not a valid claims set for this CWT type. The\n * underlying error is available on the `cause` property.\n * @throws ZodValidationError if a header map is not valid for this CWT type's header structures.\n */\n public static fromToken<T extends AnyCwt>(\n this: CwtStaticThis<T>,\n token: Uint8Array,\n structures: CwtStructures<T>\n ): T {\n const coseStructure = Cwt.decodeCoseStructure(token)\n\n const payloadBytes = coseStructure.payload\n if (!payloadBytes) {\n throw new CwtDetachedPayloadError(\n 'Cwt does not contain a payload, a detached payload is not supported for a CWT as the claims set cannot be decoded'\n )\n }\n\n let payload: CwtPayloadType<T>\n try {\n payload = decodeStructure(structures.payload, cborDecode(payloadBytes))\n } catch (error) {\n throw new CwtPayloadDecodeError(\n `Unable to decode CWT payload: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error }\n )\n }\n\n // The COSE structure only knows the base header classes, so the maps are re-read through this\n // CWT type's header structures, which is what validates them against its schema.\n const protectedHeaders = structures.protectedHeaders\n ? decodeStructure(\n structures.protectedHeaders,\n coseStructure.protectedHeaders.encodedStructure as EncodedStructureType<CwtProtectedHeadersType<T>>\n )\n : (coseStructure.protectedHeaders as CwtProtectedHeadersType<T>)\n const unprotectedHeaders = structures.unprotectedHeaders\n ? decodeStructure(\n structures.unprotectedHeaders,\n coseStructure.unprotectedHeaders.encodedStructure as EncodedStructureType<CwtUnprotectedHeadersType<T>>\n )\n : (coseStructure.unprotectedHeaders as CwtUnprotectedHeadersType<T>)\n\n return new this({\n payload,\n protectedHeaders,\n unprotectedHeaders,\n signature: coseStructure instanceof Sign1 ? coseStructure.signature : undefined,\n tag: coseStructure instanceof Mac0 ? coseStructure.tag : undefined,\n // Keep the exact bytes the issuer signed, see `originalPayloadBytes`.\n originalPayloadBytes: new Uint8Array(payloadBytes),\n })\n }\n\n /**\n * Decodes the COSE structure wrapping the CWT claims set.\n *\n * @throws CborDecodeError if the token is not valid CBOR.\n * @throws CosePayloadInvalidStructureError if the token is valid CBOR but not a COSE_Sign1/COSE_Mac0.\n */\n public static decodeCoseStructure(token: Uint8Array): Sign1 | Mac0 {\n const decoded = cborDecode<unknown>(token)\n\n // The tag 18/17 cbor-x extensions turn a COSE token into a Sign1/Mac0 instance. Anything\n // else decoded fine as CBOR but isn't a COSE token, and would otherwise be accepted here\n // and only surface much later as a confusing 'payload is missing' error.\n if (!(decoded instanceof Sign1) && !(decoded instanceof Mac0)) {\n const cwtTagHint =\n decoded instanceof Tag && decoded.tag === CWT_TAG ? ' (the CWT tag, which must be unwrapped first)' : ''\n\n throw new CosePayloadInvalidStructureError(\n `Expected a tagged COSE_Sign1 (tag ${Sign1.tag}) or COSE_Mac0 (tag ${Mac0.tag}) structure, but decoded ${describeCborValue(decoded)}${cwtTagHint}. ` +\n 'An untagged COSE structure is not supported; decode it with Sign1.decode or Mac0.decode instead.'\n )\n }\n\n return decoded\n }\n\n /**\n * The payload bytes that are signed or authenticated: the bytes as received when this CWT was\n * decoded from a token and the payload has not been modified since, and the re-encoded payload\n * otherwise.\n */\n public get payloadBytes(): Uint8Array {\n return this.originalPayloadBytes ?? this.payload.encode()\n }\n\n /**\n * Drops the retained {@link originalPayloadBytes}, so that the payload is re-encoded on the next\n * signing or verification. Call this after mutating {@link payload} in place, from a subclass or\n * from outside; assigning a new payload marks it automatically.\n */\n public markPayloadModified() {\n this.originalPayloadBytes = undefined\n }\n\n /**\n * `typ` (16), the media type of this CWT.\n *\n * Read from the protected headers only: RFC 9596 states that the `typ` parameter MUST NOT be\n * present in unprotected headers, so an unprotected one is not authoritative and reading it would\n * let anyone who can alter the token change what the token claims to be.\n *\n * @see https://www.rfc-editor.org/rfc/rfc9596.html#section-2\n */\n public get typ(): string | number | undefined {\n return this.protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.Typ)\n }\n\n /**\n * `alg` (1), the algorithm the CWT is signed or authenticated with.\n *\n * Read from the protected headers only. RFC 9052 requires `alg` to be authenticated, which for a\n * single recipient structure (COSE_Sign1 / COSE_Mac0) means the protected bucket or the externally\n * supplied data. An unprotected `alg` is attacker controlled, and is also not what\n * `Sign1.algorithm` / `Mac0.algorithm` pass to verification, so reading it here would report an\n * algorithm the signature was never checked against.\n *\n * @see https://www.rfc-editor.org/rfc/rfc9052.html#section-3.1\n */\n public get algorithm(): string | number | undefined {\n return this.protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.Algorithm)\n }\n\n /**\n * `kid` (4), a hint for which key to verify with.\n *\n * Read from the protected headers, falling back to the unprotected ones: RFC 9052 calls `kid` a\n * hint that \"is not a security-critical field\" and explicitly allows it in the unprotected bucket,\n * where it is commonly placed.\n *\n * @see https://www.rfc-editor.org/rfc/rfc9052.html#section-3.1\n */\n public get keyId(): Uint8Array | undefined {\n return (\n this.protectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.KeyId) ??\n this.unprotectedHeaders.headers.get(RegisteredCwtHeaderClaimKey.KeyId)\n )\n }\n\n /** The proof this CWT carries, whichever of the two it is: its {@link signature} or its {@link tag}. */\n public get signatureOrTag(): Uint8Array | undefined {\n return this.signature ?? this.tag\n }\n\n public get asSign1() {\n return Sign1.create({\n protectedHeaders: this.protectedHeaders,\n unprotectedHeaders: this.unprotectedHeaders,\n payload: this.payloadBytes,\n signature: this.signature,\n })\n }\n\n public get asMac0() {\n return Mac0.create({\n protectedHeaders: this.protectedHeaders,\n unprotectedHeaders: this.unprotectedHeaders,\n payload: this.payloadBytes,\n tag: this.tag,\n })\n }\n\n public async signAndEncode(\n options: { signingKey: CoseKey; algorithm?: SignatureAlgorithm; externalAad?: Uint8Array },\n ctx: Pick<Sign1Context, 'sign'>\n ) {\n return (await this.asSign1.sign(options, ctx)).encode()\n }\n\n public async authenticateAndEncode(\n options: { key: CoseKey; externalAad?: Uint8Array },\n ctx: Pick<Mac0Context, 'authenticate'>\n ) {\n return (await this.asMac0.authenticate(options, ctx)).encode()\n }\n\n /**\n * Verifies the claims of this CWT's payload. See `CwtPayload.verifyClaims` for what is checked; a\n * CWT type that narrows its payload class narrows this along with it, options included.\n *\n * This checks the claims only. {@link verify} checks the signature or authentication tag as well,\n * and is what a verifier wants: the claims of a token whose issuer has not been established mean\n * nothing.\n *\n * @throws CwtClaimVerificationError if a required claim is missing, a claim does not match what\n * was expected, or the token is outside its validity window.\n */\n public verifyClaims(options: CwtClaimsOptionsFor<Payload>): void {\n this.payload.verifyClaims(options)\n }\n\n /**\n * Verifies this CWT completely: the signature or authentication tag over the payload, and then\n * the claims in it.\n *\n * Which of the two is checked follows whether this CWT carries a {@link signature} or a\n * {@link tag}, and the matching entry of `ctx` is used, so a caller does not have to know which\n * of the two structures a token turned out to be.\n *\n * @throws CwtNotSignedError if the CWT carries neither, and so has nothing to verify.\n * @throws CwtMissingVerifyContextError if `ctx` has no entry for the structure this CWT is.\n * @throws CoseInvalidSignatureError if the signature or authentication tag does not verify.\n * @throws CwtClaimVerificationError if the claims do not, see {@link verifyClaims}.\n */\n public async verify(\n { key, externalAad, ...claimsOptions }: CwtVerifyOptions<Payload>,\n ctx: CwtVerifyContext\n ): Promise<void> {\n if (this.tag !== undefined) {\n if (!ctx.mac0) {\n throw new CwtMissingVerifyContextError(\n 'The CWT carries a COSE_Mac0 authentication tag, but no `mac0` verification context was provided'\n )\n }\n\n if (!(await this.verifyAuthenticationCode({ key, externalAad }, ctx.mac0))) {\n throw new CoseInvalidSignatureError(\n 'The authentication tag of the CWT could not be verified with the provided key'\n )\n }\n } else if (this.signature !== undefined) {\n if (!ctx.sign1) {\n throw new CwtMissingVerifyContextError(\n 'The CWT carries a COSE_Sign1 signature, but no `sign1` verification context was provided'\n )\n }\n\n if (!(await this.verifySignature({ key, externalAad }, ctx.sign1))) {\n throw new CoseInvalidSignatureError('The signature of the CWT could not be verified with the provided key')\n }\n } else {\n throw new CwtNotSignedError(\n 'The CWT carries neither a signature nor an authentication tag, so there is nothing to verify. ' +\n 'Decode a signed or authenticated token with `fromToken` to verify it.'\n )\n }\n\n // NOTE: cast because TypeScript cannot see that the rest of a generic intersection is still the\n // payload's options type.\n this.verifyClaims(claimsOptions as CwtClaimsOptionsFor<Payload>)\n }\n\n public async verifySignature(options: { key: CoseKey; externalAad?: Uint8Array }, ctx: Pick<Sign1Context, 'verify'>) {\n return await this.asSign1.verifySignature(options, ctx)\n }\n\n public async verifyAuthenticationCode(\n options: { key: CoseKey; externalAad?: Uint8Array },\n ctx: Pick<Mac0Context, 'verify'>\n ) {\n return await this.asMac0.verifyAuthenticationCode(options, ctx)\n }\n}\n\n/**\n * Builds a structure instance from its encoded form, validating it against the class's own\n * `encodingSchema`. Mirrors `CborStructure.decode`, but for a class passed in as a value rather than\n * called as a static, which is how a CWT names the structures it is made of.\n */\nfunction decodeStructure<Structure extends AnyCborStructure>(\n structureClass: CwtStructureClass<Structure>,\n encodedStructure: EncodedStructureType<Structure>\n): Structure {\n // NOTE: the instance `fromEncodedStructure` builds is used as is, rather than re-wrapped around\n // its decoded structure: a structure can carry more than that map — `ProtectedHeaders` keeps the\n // bstr it was decoded from — and re-wrapping would drop it.\n return structureClass.fromEncodedStructure(encodedStructure)\n}\n"],"mappings":";;;;;;AAGA,EAAE,OAAO,EACP,aAAa,eAAe,EAC9B,CAAC;AAED,SAAS,eAAe,OAA4B;CAClD,IAAI,CAAC,OAAO,OAAO;CAEnB,OAAO,UAAU,OAAO;EACtB,QAAQ;EACR,iBAAiB;EACjB,gBAAgB;EAChB,gBAAgB;CAClB,CAAC,CAAC,CAAC,SAAS;AACd;AAIA,IAAa,kBAAb,cAAqC,MAAM;CAGzC,YAAY,SAAiB,UAAqB;EAChD,MAAM,OAAO;EAEb,MAAM,iBAAiB,WAAW,eAAe,QAAQ,IAAI;EAC7D,KAAK,UAAU,GAAG,QAAQ,IAAI;EAE9B,OAAO,eAAe,MAAM,YAAY;GACtC,OAAO;GACP,UAAU;GACV,YAAY;EACd,CAAC;CACH;AACF;;AC/BA,MAAa,cAAc,EAAE,WAA+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;;;CAaA,aAAoB,SAA6C;EAC/D,KAAK,QAAQ,aAAa,OAAO;CACnC;;;;;;;;;;;;;;CAeA,MAAa,OACX,EAAE,KAAK,aAAa,GAAG,iBACvB,KACe;EACf,IAAI,KAAK,QAAQ,KAAA,GAAW;GAC1B,IAAI,CAAC,IAAI,MACP,MAAM,IAAI,6BACR,iGACF;GAGF,IAAI,CAAE,MAAM,KAAK,yBAAyB;IAAE;IAAK;GAAY,GAAG,IAAI,IAAI,GACtE,MAAM,IAAI,0BACR,+EACF;EAEJ,OAAO,IAAI,KAAK,cAAc,KAAA,GAAW;GACvC,IAAI,CAAC,IAAI,OACP,MAAM,IAAI,6BACR,0FACF;GAGF,IAAI,CAAE,MAAM,KAAK,gBAAgB;IAAE;IAAK;GAAY,GAAG,IAAI,KAAK,GAC9D,MAAM,IAAI,0BAA0B,sEAAsE;EAE9G,OACE,MAAM,IAAI,kBACR,qKAEF;EAKF,KAAK,aAAa,aAA6C;CACjE;CAEA,MAAa,gBAAgB,SAAqD,KAAmC;EACnH,OAAO,MAAM,KAAK,QAAQ,gBAAgB,SAAS,GAAG;CACxD;CAEA,MAAa,yBACX,SACA,KACA;EACA,OAAO,MAAM,KAAK,OAAO,yBAAyB,SAAS,GAAG;CAChE;AACF;;;;;;AAOA,SAAS,gBACP,gBACA,kBACW;CAIX,OAAO,eAAe,qBAAqB,gBAAgB;AAC7D"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@owf/cose",
|
|
3
|
-
"version": "0.7.0
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"files": [
|
|
5
5
|
"dist"
|
|
6
6
|
],
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"cbor-x": "^1.6.8",
|
|
26
26
|
"zod": "^4.6.7",
|
|
27
27
|
"zod-validation-error": "^5.0.0",
|
|
28
|
-
"@owf/identity-common": "0.7.0
|
|
28
|
+
"@owf/identity-common": "0.7.0"
|
|
29
29
|
},
|
|
30
30
|
"scripts": {
|
|
31
31
|
"build": "tsdown src/index.ts --format esm --dts --sourcemap"
|