@owf/cose 0.3.2-alpha-20260709122021 → 0.3.2-alpha-20260713153517
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.cjs +2 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -22
- package/dist/index.d.mts +9 -22
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1114,7 +1114,8 @@ var Cwt = class Cwt {
|
|
|
1114
1114
|
return new Cwt(options);
|
|
1115
1115
|
}
|
|
1116
1116
|
static fromToken(token) {
|
|
1117
|
-
|
|
1117
|
+
const decoded = cborDecode(token);
|
|
1118
|
+
return new Cwt(decoded);
|
|
1118
1119
|
}
|
|
1119
1120
|
get asSign1() {
|
|
1120
1121
|
return Sign1.create(this.options);
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["z","z","Encoder","z","#data","#buffer","Tag","z","z","z","z","z","base64url","z","z","z"],"sources":["../src/utils/zod-error.ts","../src/utils/zod.ts","../src/cbor/parser.ts","../src/cbor/data-item.ts","../src/cbor/cbor-structure.ts","../src/cbor/models/date.ts","../src/cbor/models/date-only.ts","../src/cose/claims/default.ts","../src/cose/error.ts","../src/cose/headers/defaults.ts","../src/utils/typed-map.ts","../src/cose/headers/header-claims.ts","../src/cose/headers/protected-headers.ts","../src/cose/headers/unprotected-headers.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 { Encoder, type Options } from 'cbor-x'\nimport { DataItem } from './data-item'\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 const decoded = enc.decode(input)\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 return Uint8Array.from(enc.encode(obj))\n}\n","import { addExtension } from 'cbor-x'\nimport z from 'zod'\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 { Tag } from 'cbor-x'\nimport { z } from 'zod'\nimport {\n decodeStructureWithErrorHandling,\n encodeStructureWithErrorHandling,\n parseStructureWithErrorHandling,\n} from '../utils/zod'\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 { 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","/**\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","// biome-ignore format: no explanation\nclass CoseError extends Error {\n constructor(message: string = new.target.name) {\n super(message)\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 {}\nexport class CoseKeyTypeNotSupportedForPrivateKeyExtractionError extends CoseError {}\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 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 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 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 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 return this.map.delete(key)\n }\n\n clear(): void {\n this.map.clear()\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\ntype 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\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 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 * 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 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 '${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 '${key}' to be defined.`,\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\n path: [`${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","import z from 'zod'\nimport { type TypedMap, typedMap } 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 * Schema for the known COSE header claims (RFC 9052 Section 3.1 / RFC 9360 / the IANA COSE Header\n * Parameters registry). Shared by the protected and unprotected header 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(\n [\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 [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 { allowAdditionalKeys: true }\n)\n\nexport type CoseHeaderClaims = z.infer<typeof coseHeaderClaimsSchema>\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 * e.g. a status list's `typ`). The typed claims are still validated at decode by\n * `coseHeaderClaimsSchema`; this view only governs typed access.\n */\nexport type CoseHeaders = OpenIntegerKeys<CoseHeaderClaims>\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport { cborDecode, cborEncode } from '../../cbor/parser.js'\nimport { 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\nexport type ProtectedHeaderOptions = {\n protectedHeaders?: Map<number, unknown>\n}\n\nexport class ProtectedHeaders extends CborStructure<\n ProtectedHeadersEncodedStructure,\n ProtectedHeadersDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(protectedHeadersEncodedStructure, coseHeaderClaimsSchema.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.toMap()) as Uint8Array<ArrayBuffer>,\n decode: (encoded) => TypedMap.fromMap(cborDecode(encoded) as Map<number, unknown>),\n })\n }\n\n public get headers(): CoseHeaders {\n return this.structure as unknown as CoseHeaders\n }\n\n public static create(options: ProtectedHeaderOptions) {\n return ProtectedHeaders.fromDecodedStructure(TypedMap.fromMap(options.protectedHeaders ?? new Map()))\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport { 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\nexport class UnprotectedHeaders extends CborStructure<\n UnprotectedHeadersEncodedStructure,\n UnprotectedHeadersDecodedStructure\n> {\n public static override get encodingSchema() {\n return coseHeaderClaimsSchema\n }\n\n public get headers(): CoseHeaders {\n return this.structure as unknown as CoseHeaders\n }\n\n public static create(options: UnprotectedHeaderOptions) {\n return UnprotectedHeaders.fromDecodedStructure(TypedMap.fromMap(options.unprotectedHeaders ?? new Map()))\n }\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 [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\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 externalAad?: Uint8Array\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 externalAad?: Uint8Array\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 */\n public toBeAuthenticated(options?: { detachedPayload?: 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: this.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 // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\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 rawStructure instanceof Mac0\n ? rawStructure.decodedStructure\n : Mac0.fromEncodedStructure(rawStructure as EncodedStructureType<T>).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 // biome-ignore lint/complexity/noThisInStatic: this.create is intentional for subclass support\n const mac0 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n tag: options.tag ?? new Uint8Array(),\n })\n\n mac0.externalAad = options.externalAad\n\n return mac0\n }\n\n public async authenticate(\n options: {\n key: CoseKey | Uint8Array\n detachedPayload?: Uint8Array\n algorithm?: MacAlgorithm\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: this.externalAad,\n }),\n algorithm: macAlgorithm,\n key: options.key,\n })\n return this\n }\n\n public async verifyAuthenticationCode(\n { key, detachedPayload }: { key: CoseKey; detachedPayload?: 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 }),\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 { addExtension } from 'cbor-x'\nimport z from 'zod'\nimport {\n type AnyCborStructure,\n CborStructure,\n type CborStructureStaticThis,\n cborDecode,\n cborEncode,\n type EncodedStructureType,\n} from '../cbor'\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 externalAad?: Uint8Array\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 externalAad?: Uint8Array\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 */\n public toBeSigned(options?: { detachedPayload?: 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: this.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 // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\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 rawStructure instanceof Sign1\n ? rawStructure.decodedStructure\n : Sign1.fromEncodedStructure(rawStructure as EncodedStructureType<T>).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 }: { key: CoseKey; detachedPayload?: 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 }),\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 // biome-ignore lint/complexity/noThisInStatic: this.create is intentional for subclass support\n const sign1 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n signature: options.signature ?? new Uint8Array(),\n })\n\n sign1.externalAad = options.externalAad\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 { cborDecode } from '../cbor'\nimport type { CoseKey } from './key'\nimport { Mac0, type Mac0Context, type Mac0Options } from './mac0'\nimport { Sign1, type Sign1Context, type Sign1Options } from './sign1'\n\nexport type CwtOptions = Sign1Options | Mac0Options\n\nexport class Cwt {\n public constructor(private options: CwtOptions) {}\n\n public static create(options: CwtOptions) {\n return new Cwt(options)\n }\n\n public static fromToken(token: Uint8Array) {\n const decoded = cborDecode<Sign1 | Mac0>(token)\n return new Cwt(decoded)\n }\n\n public get asSign1() {\n return Sign1.create(this.options)\n }\n\n public get asMac0() {\n return Mac0.create(this.options)\n }\n\n public get payload() {\n return this.options.payload\n }\n\n public get protectedHeaders() {\n return this.options.protectedHeaders\n }\n\n public get unprotectedHeaders() {\n return this.options.unprotectedHeaders\n }\n\n public get signatureOrTag() {\n return 'signature' in this.options ? this.options.signature : 'tag' in this.options ? this.options.tag : undefined\n }\n\n public async verifySignature({ key }: { key: CoseKey }, ctx: Pick<Sign1Context, 'verify'>) {\n return await this.asSign1.verifySignature({ key }, ctx)\n }\n\n public async verifyAuthenticationCode({ key }: { key: CoseKey }, ctx: Pick<Mac0Context, 'verify'>) {\n return await this.asMac0.verifyAuthenticationCode({ key }, ctx)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGAA,IAAAA,QAAE,OAAO,EACP,cAAA,GAAA,qBAAA,eAAA,CAA4B,EAC9B,CAAC;AAED,SAAS,eAAe,OAA4B;CAClD,IAAI,CAAC,OAAO,OAAO;CAEnB,QAAA,GAAA,qBAAA,UAAA,CAAiB,OAAO;EACtB,QAAQ;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;CACjC;CAEA,IAAW,UAAU;EACnB,OAAO,KAAK,QAAQ;CACtB;CAEA,IAAW,mBAAmB;EAC5B,OAAO,KAAK,QAAQ;CACtB;CAEA,IAAW,qBAAqB;EAC9B,OAAO,KAAK,QAAQ;CACtB;CAEA,IAAW,iBAAiB;EAC1B,OAAO,eAAe,KAAK,UAAU,KAAK,QAAQ,YAAY,SAAS,KAAK,UAAU,KAAK,QAAQ,MAAM,KAAA;CAC3G;CAEA,MAAa,gBAAgB,EAAE,OAAyB,KAAmC;EACzF,OAAO,MAAM,KAAK,QAAQ,gBAAgB,EAAE,IAAI,GAAG,GAAG;CACxD;CAEA,MAAa,yBAAyB,EAAE,OAAyB,KAAkC;EACjG,OAAO,MAAM,KAAK,OAAO,yBAAyB,EAAE,IAAI,GAAG,GAAG;CAChE;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["z","z","Encoder","z","#data","#buffer","Tag","z","z","z","z","z","base64url","z","z","z"],"sources":["../src/utils/zod-error.ts","../src/utils/zod.ts","../src/cbor/parser.ts","../src/cbor/data-item.ts","../src/cbor/cbor-structure.ts","../src/cbor/models/date.ts","../src/cbor/models/date-only.ts","../src/cose/claims/default.ts","../src/cose/error.ts","../src/cose/headers/defaults.ts","../src/utils/typed-map.ts","../src/cose/headers/header-claims.ts","../src/cose/headers/protected-headers.ts","../src/cose/headers/unprotected-headers.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 { Encoder, type Options } from 'cbor-x'\nimport { DataItem } from './data-item'\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 const decoded = enc.decode(input)\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 return Uint8Array.from(enc.encode(obj))\n}\n","import { addExtension } from 'cbor-x'\nimport z from 'zod'\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 { Tag } from 'cbor-x'\nimport { z } from 'zod'\nimport {\n decodeStructureWithErrorHandling,\n encodeStructureWithErrorHandling,\n parseStructureWithErrorHandling,\n} from '../utils/zod'\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 { 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","/**\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","// biome-ignore format: no explanation\nclass CoseError extends Error {\n constructor(message: string = new.target.name) {\n super(message)\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 {}\nexport class CoseKeyTypeNotSupportedForPrivateKeyExtractionError extends CoseError {}\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 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 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 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 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 return this.map.delete(key)\n }\n\n clear(): void {\n this.map.clear()\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\ntype 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\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 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 * 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 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 '${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 '${key}' to be defined.`,\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\n path: [`${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","import z from 'zod'\nimport { type TypedMap, typedMap } 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 * Schema for the known COSE header claims (RFC 9052 Section 3.1 / RFC 9360 / the IANA COSE Header\n * Parameters registry). Shared by the protected and unprotected header 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(\n [\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 [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 { allowAdditionalKeys: true }\n)\n\nexport type CoseHeaderClaims = z.infer<typeof coseHeaderClaimsSchema>\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 * e.g. a status list's `typ`). The typed claims are still validated at decode by\n * `coseHeaderClaimsSchema`; this view only governs typed access.\n */\nexport type CoseHeaders = OpenIntegerKeys<CoseHeaderClaims>\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport { cborDecode, cborEncode } from '../../cbor/parser.js'\nimport { 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\nexport type ProtectedHeaderOptions = {\n protectedHeaders?: Map<number, unknown>\n}\n\nexport class ProtectedHeaders extends CborStructure<\n ProtectedHeadersEncodedStructure,\n ProtectedHeadersDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(protectedHeadersEncodedStructure, coseHeaderClaimsSchema.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.toMap()) as Uint8Array<ArrayBuffer>,\n decode: (encoded) => TypedMap.fromMap(cborDecode(encoded) as Map<number, unknown>),\n })\n }\n\n public get headers(): CoseHeaders {\n return this.structure as unknown as CoseHeaders\n }\n\n public static create(options: ProtectedHeaderOptions) {\n return ProtectedHeaders.fromDecodedStructure(TypedMap.fromMap(options.protectedHeaders ?? new Map()))\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport { 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\nexport class UnprotectedHeaders extends CborStructure<\n UnprotectedHeadersEncodedStructure,\n UnprotectedHeadersDecodedStructure\n> {\n public static override get encodingSchema() {\n return coseHeaderClaimsSchema\n }\n\n public get headers(): CoseHeaders {\n return this.structure as unknown as CoseHeaders\n }\n\n public static create(options: UnprotectedHeaderOptions) {\n return UnprotectedHeaders.fromDecodedStructure(TypedMap.fromMap(options.unprotectedHeaders ?? new Map()))\n }\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 [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\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 externalAad?: Uint8Array\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 externalAad?: Uint8Array\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 */\n public toBeAuthenticated(options?: { detachedPayload?: 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: this.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 // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\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 rawStructure instanceof Mac0\n ? rawStructure.decodedStructure\n : Mac0.fromEncodedStructure(rawStructure as EncodedStructureType<T>).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 // biome-ignore lint/complexity/noThisInStatic: this.create is intentional for subclass support\n const mac0 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n tag: options.tag ?? new Uint8Array(),\n })\n\n mac0.externalAad = options.externalAad\n\n return mac0\n }\n\n public async authenticate(\n options: {\n key: CoseKey | Uint8Array\n detachedPayload?: Uint8Array\n algorithm?: MacAlgorithm\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: this.externalAad,\n }),\n algorithm: macAlgorithm,\n key: options.key,\n })\n return this\n }\n\n public async verifyAuthenticationCode(\n { key, detachedPayload }: { key: CoseKey; detachedPayload?: 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 }),\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 { addExtension } from 'cbor-x'\nimport z from 'zod'\nimport {\n type AnyCborStructure,\n CborStructure,\n type CborStructureStaticThis,\n cborDecode,\n cborEncode,\n type EncodedStructureType,\n} from '../cbor'\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 externalAad?: Uint8Array\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 externalAad?: Uint8Array\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 */\n public toBeSigned(options?: { detachedPayload?: 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: this.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 // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\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 rawStructure instanceof Sign1\n ? rawStructure.decodedStructure\n : Sign1.fromEncodedStructure(rawStructure as EncodedStructureType<T>).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 }: { key: CoseKey; detachedPayload?: 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 }),\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 // biome-ignore lint/complexity/noThisInStatic: this.create is intentional for subclass support\n const sign1 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n signature: options.signature ?? new Uint8Array(),\n })\n\n sign1.externalAad = options.externalAad\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 { cborDecode } from '../cbor'\nimport type { CoseKey } from './key'\nimport { Mac0, type Mac0Context, type Mac0Options } from './mac0'\nimport { Sign1, type Sign1Context, type Sign1Options } from './sign1'\n\nexport type CwtOptions = Sign1Options | Mac0Options\n\nexport class Cwt {\n public constructor(private options: CwtOptions) {}\n\n public static create(options: CwtOptions) {\n return new Cwt(options)\n }\n\n public static fromToken(token: Uint8Array) {\n const decoded = cborDecode<Sign1 | Mac0>(token)\n return new Cwt(decoded)\n }\n\n public get asSign1() {\n return Sign1.create(this.options)\n }\n\n public get asMac0() {\n return Mac0.create(this.options)\n }\n\n public get payload() {\n return this.options.payload\n }\n\n public get protectedHeaders() {\n return this.options.protectedHeaders\n }\n\n public get unprotectedHeaders() {\n return this.options.unprotectedHeaders\n }\n\n public get signatureOrTag() {\n return 'signature' in this.options ? this.options.signature : 'tag' in this.options ? this.options.tag : undefined\n }\n\n public async verifySignature({ key }: { key: CoseKey }, ctx: Pick<Sign1Context, 'verify'>) {\n return await this.asSign1.verifySignature({ key }, ctx)\n }\n\n public async verifyAuthenticationCode({ key }: { key: CoseKey }, ctx: Pick<Mac0Context, 'verify'>) {\n return await this.asMac0.verifyAuthenticationCode({ key }, ctx)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGAA,IAAAA,QAAE,OAAO,EACP,cAAA,GAAA,qBAAA,eAAA,CAA4B,EAC9B,CAAC;AAED,SAAS,eAAe,OAA4B;CAClD,IAAI,CAAC,OAAO,OAAO;CAEnB,QAAA,GAAA,qBAAA,UAAA,CAAiB,OAAO;EACtB,QAAQ;EACR,iBAAiB;EACjB,gBAAgB;EAChB,gBAAgB;CAClB,CAAC,CAAC,CAAC,SAAS;AACd;AAIA,I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AW,mBAAmB;EAC5B,OAAO,KAAK,QAAQ;CACtB;CAEA,IAAW,qBAAqB;EAC9B,OAAO,KAAK,QAAQ;CACtB;CAEA,IAAW,iBAAiB;EAC1B,OAAO,eAAe,KAAK,UAAU,KAAK,QAAQ,YAAY,SAAS,KAAK,UAAU,KAAK,QAAQ,MAAM,KAAA;CAC3G;CAEA,MAAa,gBAAgB,EAAE,OAAyB,KAAmC;EACzF,OAAO,MAAM,KAAK,QAAQ,gBAAgB,EAAE,IAAI,GAAG,GAAG;CACxD;CAEA,MAAa,yBAAyB,EAAE,OAAyB,KAAkC;EACjG,OAAO,MAAM,KAAK,OAAO,yBAAyB,EAAE,IAAI,GAAG,GAAG;CAChE;AACF"}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Options, addExtension } from "cbor-x";
|
|
2
2
|
import z, { ZodError, z as z$1 } from "zod";
|
|
3
|
+
import "zod/v4/core";
|
|
3
4
|
//#region src/cbor/cbor-structure.d.ts
|
|
4
5
|
type CborEncodeOptions = {
|
|
5
6
|
asDataItem?: boolean;
|
|
@@ -217,11 +218,11 @@ declare class TypedMap<Schema extends Record<PropertyKey, any>, OptionalKeys ext
|
|
|
217
218
|
[Symbol.iterator](): IterableIterator<[keyof Schema, Schema[keyof Schema]]>;
|
|
218
219
|
toMap(): Map<keyof Schema, Schema[keyof Schema]>;
|
|
219
220
|
}
|
|
220
|
-
type EntriesArrayToSchema<T extends ReadonlyArray<readonly [any, any]>> = { [K in T[number][0]]: Extract<T[number], readonly [K, any]>[1] };
|
|
221
|
+
type EntriesArrayToSchema<T extends ReadonlyArray<readonly [any, any]>> = { [K in T[number][0]]: Extract<T[number], readonly [K, any]>[1]; };
|
|
221
222
|
type EntriesBase = ReadonlyArray<readonly [string | number, z$1.ZodType<any>]>;
|
|
222
|
-
type InferredEntries<Entries extends EntriesBase> = { [K in keyof Entries]: readonly [Entries[K][0], z$1.infer<Entries[K][1]>] };
|
|
223
|
+
type InferredEntries<Entries extends EntriesBase> = { [K in keyof Entries]: readonly [Entries[K][0], z$1.infer<Entries[K][1]>]; };
|
|
223
224
|
type InferredSchema<Entries extends EntriesBase> = EntriesArrayToSchema<InferredEntries<Entries>>;
|
|
224
|
-
type OptionalKeys<Entries extends EntriesBase> = Entries[number] extends infer E ? E extends readonly [infer K, infer V] ? V extends z$1.ZodExactOptional<any> ? K : never : never : never;
|
|
225
|
+
type OptionalKeys<Entries extends EntriesBase> = Entries[number] extends (infer E) ? E extends readonly [infer K, infer V] ? V extends z$1.ZodExactOptional<any> ? K : never : never : never;
|
|
225
226
|
/**
|
|
226
227
|
* Utility function to create a typed map codec.
|
|
227
228
|
* Takes an array of [key, valueSchema] entries to support any key type (including non-string keys for CBOR).
|
|
@@ -235,11 +236,7 @@ type OptionalKeys<Entries extends EntriesBase> = Entries[number] extends infer E
|
|
|
235
236
|
*
|
|
236
237
|
* The resulting schema validates a Map and transforms it to TypedMap<Schema, never>.
|
|
237
238
|
*/
|
|
238
|
-
declare function typedMap<const Entries extends EntriesBase>(entries: Entries, {
|
|
239
|
-
allowAdditionalKeys,
|
|
240
|
-
encode,
|
|
241
|
-
decode
|
|
242
|
-
}?: {
|
|
239
|
+
declare function typedMap<const Entries extends EntriesBase>(entries: Entries, { allowAdditionalKeys, encode, decode }?: {
|
|
243
240
|
/**
|
|
244
241
|
* Whether to allow additional keys in the typed map
|
|
245
242
|
*
|
|
@@ -604,10 +601,7 @@ declare class Mac0 extends CborStructure<Mac0EncodedStructure, Mac0DecodedStruct
|
|
|
604
601
|
detachedPayload?: Uint8Array;
|
|
605
602
|
algorithm?: MacAlgorithm;
|
|
606
603
|
}, ctx: Pick<Mac0Context, 'authenticate'>): Promise<this>;
|
|
607
|
-
verifyAuthenticationCode({
|
|
608
|
-
key,
|
|
609
|
-
detachedPayload
|
|
610
|
-
}: {
|
|
604
|
+
verifyAuthenticationCode({ key, detachedPayload }: {
|
|
611
605
|
key: CoseKey;
|
|
612
606
|
detachedPayload?: Uint8Array;
|
|
613
607
|
}, ctx: Pick<Mac0Context, 'verify'>): Promise<boolean>;
|
|
@@ -687,10 +681,7 @@ declare class Sign1 extends CborStructure<Sign1EncodedStructure, Sign1DecodedStr
|
|
|
687
681
|
get algorithm(): SignatureAlgorithm | undefined;
|
|
688
682
|
get jwaAlgorithm(): keyof typeof SignatureAlgorithm | undefined;
|
|
689
683
|
get x5chain(): Uint8Array<ArrayBufferLike>[] | undefined;
|
|
690
|
-
verifySignature({
|
|
691
|
-
key,
|
|
692
|
-
detachedPayload
|
|
693
|
-
}: {
|
|
684
|
+
verifySignature({ key, detachedPayload }: {
|
|
694
685
|
key: CoseKey;
|
|
695
686
|
detachedPayload?: Uint8Array;
|
|
696
687
|
}, ctx: Pick<Sign1Context, 'verify'>): Promise<boolean>;
|
|
@@ -716,14 +707,10 @@ declare class Cwt {
|
|
|
716
707
|
get protectedHeaders(): Map<number, unknown> | ProtectedHeaders | undefined;
|
|
717
708
|
get unprotectedHeaders(): Map<number, unknown> | UnprotectedHeaders | undefined;
|
|
718
709
|
get signatureOrTag(): Uint8Array<ArrayBufferLike> | undefined;
|
|
719
|
-
verifySignature({
|
|
720
|
-
key
|
|
721
|
-
}: {
|
|
710
|
+
verifySignature({ key }: {
|
|
722
711
|
key: CoseKey;
|
|
723
712
|
}, ctx: Pick<Sign1Context, 'verify'>): Promise<boolean>;
|
|
724
|
-
verifyAuthenticationCode({
|
|
725
|
-
key
|
|
726
|
-
}: {
|
|
713
|
+
verifyAuthenticationCode({ key }: {
|
|
727
714
|
key: CoseKey;
|
|
728
715
|
}, ctx: Pick<Mac0Context, 'verify'>): Promise<boolean>;
|
|
729
716
|
}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Options, addExtension } from "cbor-x";
|
|
2
2
|
import z, { ZodError, z as z$1 } from "zod";
|
|
3
|
+
import "zod/v4/core";
|
|
3
4
|
//#region src/cbor/cbor-structure.d.ts
|
|
4
5
|
type CborEncodeOptions = {
|
|
5
6
|
asDataItem?: boolean;
|
|
@@ -217,11 +218,11 @@ declare class TypedMap<Schema extends Record<PropertyKey, any>, OptionalKeys ext
|
|
|
217
218
|
[Symbol.iterator](): IterableIterator<[keyof Schema, Schema[keyof Schema]]>;
|
|
218
219
|
toMap(): Map<keyof Schema, Schema[keyof Schema]>;
|
|
219
220
|
}
|
|
220
|
-
type EntriesArrayToSchema<T extends ReadonlyArray<readonly [any, any]>> = { [K in T[number][0]]: Extract<T[number], readonly [K, any]>[1] };
|
|
221
|
+
type EntriesArrayToSchema<T extends ReadonlyArray<readonly [any, any]>> = { [K in T[number][0]]: Extract<T[number], readonly [K, any]>[1]; };
|
|
221
222
|
type EntriesBase = ReadonlyArray<readonly [string | number, z$1.ZodType<any>]>;
|
|
222
|
-
type InferredEntries<Entries extends EntriesBase> = { [K in keyof Entries]: readonly [Entries[K][0], z$1.infer<Entries[K][1]>] };
|
|
223
|
+
type InferredEntries<Entries extends EntriesBase> = { [K in keyof Entries]: readonly [Entries[K][0], z$1.infer<Entries[K][1]>]; };
|
|
223
224
|
type InferredSchema<Entries extends EntriesBase> = EntriesArrayToSchema<InferredEntries<Entries>>;
|
|
224
|
-
type OptionalKeys<Entries extends EntriesBase> = Entries[number] extends infer E ? E extends readonly [infer K, infer V] ? V extends z$1.ZodExactOptional<any> ? K : never : never : never;
|
|
225
|
+
type OptionalKeys<Entries extends EntriesBase> = Entries[number] extends (infer E) ? E extends readonly [infer K, infer V] ? V extends z$1.ZodExactOptional<any> ? K : never : never : never;
|
|
225
226
|
/**
|
|
226
227
|
* Utility function to create a typed map codec.
|
|
227
228
|
* Takes an array of [key, valueSchema] entries to support any key type (including non-string keys for CBOR).
|
|
@@ -235,11 +236,7 @@ type OptionalKeys<Entries extends EntriesBase> = Entries[number] extends infer E
|
|
|
235
236
|
*
|
|
236
237
|
* The resulting schema validates a Map and transforms it to TypedMap<Schema, never>.
|
|
237
238
|
*/
|
|
238
|
-
declare function typedMap<const Entries extends EntriesBase>(entries: Entries, {
|
|
239
|
-
allowAdditionalKeys,
|
|
240
|
-
encode,
|
|
241
|
-
decode
|
|
242
|
-
}?: {
|
|
239
|
+
declare function typedMap<const Entries extends EntriesBase>(entries: Entries, { allowAdditionalKeys, encode, decode }?: {
|
|
243
240
|
/**
|
|
244
241
|
* Whether to allow additional keys in the typed map
|
|
245
242
|
*
|
|
@@ -604,10 +601,7 @@ declare class Mac0 extends CborStructure<Mac0EncodedStructure, Mac0DecodedStruct
|
|
|
604
601
|
detachedPayload?: Uint8Array;
|
|
605
602
|
algorithm?: MacAlgorithm;
|
|
606
603
|
}, ctx: Pick<Mac0Context, 'authenticate'>): Promise<this>;
|
|
607
|
-
verifyAuthenticationCode({
|
|
608
|
-
key,
|
|
609
|
-
detachedPayload
|
|
610
|
-
}: {
|
|
604
|
+
verifyAuthenticationCode({ key, detachedPayload }: {
|
|
611
605
|
key: CoseKey;
|
|
612
606
|
detachedPayload?: Uint8Array;
|
|
613
607
|
}, ctx: Pick<Mac0Context, 'verify'>): Promise<boolean>;
|
|
@@ -687,10 +681,7 @@ declare class Sign1 extends CborStructure<Sign1EncodedStructure, Sign1DecodedStr
|
|
|
687
681
|
get algorithm(): SignatureAlgorithm | undefined;
|
|
688
682
|
get jwaAlgorithm(): keyof typeof SignatureAlgorithm | undefined;
|
|
689
683
|
get x5chain(): Uint8Array<ArrayBufferLike>[] | undefined;
|
|
690
|
-
verifySignature({
|
|
691
|
-
key,
|
|
692
|
-
detachedPayload
|
|
693
|
-
}: {
|
|
684
|
+
verifySignature({ key, detachedPayload }: {
|
|
694
685
|
key: CoseKey;
|
|
695
686
|
detachedPayload?: Uint8Array;
|
|
696
687
|
}, ctx: Pick<Sign1Context, 'verify'>): Promise<boolean>;
|
|
@@ -716,14 +707,10 @@ declare class Cwt {
|
|
|
716
707
|
get protectedHeaders(): Map<number, unknown> | ProtectedHeaders | undefined;
|
|
717
708
|
get unprotectedHeaders(): Map<number, unknown> | UnprotectedHeaders | undefined;
|
|
718
709
|
get signatureOrTag(): Uint8Array<ArrayBufferLike> | undefined;
|
|
719
|
-
verifySignature({
|
|
720
|
-
key
|
|
721
|
-
}: {
|
|
710
|
+
verifySignature({ key }: {
|
|
722
711
|
key: CoseKey;
|
|
723
712
|
}, ctx: Pick<Sign1Context, 'verify'>): Promise<boolean>;
|
|
724
|
-
verifyAuthenticationCode({
|
|
725
|
-
key
|
|
726
|
-
}: {
|
|
713
|
+
verifyAuthenticationCode({ key }: {
|
|
727
714
|
key: CoseKey;
|
|
728
715
|
}, ctx: Pick<Mac0Context, 'verify'>): Promise<boolean>;
|
|
729
716
|
}
|
package/dist/index.mjs
CHANGED
|
@@ -1090,7 +1090,8 @@ var Cwt = class Cwt {
|
|
|
1090
1090
|
return new Cwt(options);
|
|
1091
1091
|
}
|
|
1092
1092
|
static fromToken(token) {
|
|
1093
|
-
|
|
1093
|
+
const decoded = cborDecode(token);
|
|
1094
|
+
return new Cwt(decoded);
|
|
1094
1095
|
}
|
|
1095
1096
|
get asSign1() {
|
|
1096
1097
|
return Sign1.create(this.options);
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["#data","#buffer","addExtension","z","addExtension","addExtension","z","z","z","addExtension"],"sources":["../src/utils/zod-error.ts","../src/utils/zod.ts","../src/cbor/parser.ts","../src/cbor/data-item.ts","../src/cbor/cbor-structure.ts","../src/cbor/models/date.ts","../src/cbor/models/date-only.ts","../src/cose/claims/default.ts","../src/cose/error.ts","../src/cose/headers/defaults.ts","../src/utils/typed-map.ts","../src/cose/headers/header-claims.ts","../src/cose/headers/protected-headers.ts","../src/cose/headers/unprotected-headers.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 { Encoder, type Options } from 'cbor-x'\nimport { DataItem } from './data-item'\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 const decoded = enc.decode(input)\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 return Uint8Array.from(enc.encode(obj))\n}\n","import { addExtension } from 'cbor-x'\nimport z from 'zod'\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 { Tag } from 'cbor-x'\nimport { z } from 'zod'\nimport {\n decodeStructureWithErrorHandling,\n encodeStructureWithErrorHandling,\n parseStructureWithErrorHandling,\n} from '../utils/zod'\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 { 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","/**\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","// biome-ignore format: no explanation\nclass CoseError extends Error {\n constructor(message: string = new.target.name) {\n super(message)\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 {}\nexport class CoseKeyTypeNotSupportedForPrivateKeyExtractionError extends CoseError {}\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 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 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 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 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 return this.map.delete(key)\n }\n\n clear(): void {\n this.map.clear()\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\ntype 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\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 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 * 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 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 '${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 '${key}' to be defined.`,\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\n path: [`${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","import z from 'zod'\nimport { type TypedMap, typedMap } 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 * Schema for the known COSE header claims (RFC 9052 Section 3.1 / RFC 9360 / the IANA COSE Header\n * Parameters registry). Shared by the protected and unprotected header 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(\n [\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 [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 { allowAdditionalKeys: true }\n)\n\nexport type CoseHeaderClaims = z.infer<typeof coseHeaderClaimsSchema>\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 * e.g. a status list's `typ`). The typed claims are still validated at decode by\n * `coseHeaderClaimsSchema`; this view only governs typed access.\n */\nexport type CoseHeaders = OpenIntegerKeys<CoseHeaderClaims>\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport { cborDecode, cborEncode } from '../../cbor/parser.js'\nimport { 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\nexport type ProtectedHeaderOptions = {\n protectedHeaders?: Map<number, unknown>\n}\n\nexport class ProtectedHeaders extends CborStructure<\n ProtectedHeadersEncodedStructure,\n ProtectedHeadersDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(protectedHeadersEncodedStructure, coseHeaderClaimsSchema.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.toMap()) as Uint8Array<ArrayBuffer>,\n decode: (encoded) => TypedMap.fromMap(cborDecode(encoded) as Map<number, unknown>),\n })\n }\n\n public get headers(): CoseHeaders {\n return this.structure as unknown as CoseHeaders\n }\n\n public static create(options: ProtectedHeaderOptions) {\n return ProtectedHeaders.fromDecodedStructure(TypedMap.fromMap(options.protectedHeaders ?? new Map()))\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport { 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\nexport class UnprotectedHeaders extends CborStructure<\n UnprotectedHeadersEncodedStructure,\n UnprotectedHeadersDecodedStructure\n> {\n public static override get encodingSchema() {\n return coseHeaderClaimsSchema\n }\n\n public get headers(): CoseHeaders {\n return this.structure as unknown as CoseHeaders\n }\n\n public static create(options: UnprotectedHeaderOptions) {\n return UnprotectedHeaders.fromDecodedStructure(TypedMap.fromMap(options.unprotectedHeaders ?? new Map()))\n }\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 [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\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 externalAad?: Uint8Array\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 externalAad?: Uint8Array\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 */\n public toBeAuthenticated(options?: { detachedPayload?: 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: this.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 // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\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 rawStructure instanceof Mac0\n ? rawStructure.decodedStructure\n : Mac0.fromEncodedStructure(rawStructure as EncodedStructureType<T>).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 // biome-ignore lint/complexity/noThisInStatic: this.create is intentional for subclass support\n const mac0 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n tag: options.tag ?? new Uint8Array(),\n })\n\n mac0.externalAad = options.externalAad\n\n return mac0\n }\n\n public async authenticate(\n options: {\n key: CoseKey | Uint8Array\n detachedPayload?: Uint8Array\n algorithm?: MacAlgorithm\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: this.externalAad,\n }),\n algorithm: macAlgorithm,\n key: options.key,\n })\n return this\n }\n\n public async verifyAuthenticationCode(\n { key, detachedPayload }: { key: CoseKey; detachedPayload?: 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 }),\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 { addExtension } from 'cbor-x'\nimport z from 'zod'\nimport {\n type AnyCborStructure,\n CborStructure,\n type CborStructureStaticThis,\n cborDecode,\n cborEncode,\n type EncodedStructureType,\n} from '../cbor'\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 externalAad?: Uint8Array\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 externalAad?: Uint8Array\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 */\n public toBeSigned(options?: { detachedPayload?: 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: this.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 // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\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 rawStructure instanceof Sign1\n ? rawStructure.decodedStructure\n : Sign1.fromEncodedStructure(rawStructure as EncodedStructureType<T>).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 }: { key: CoseKey; detachedPayload?: 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 }),\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 // biome-ignore lint/complexity/noThisInStatic: this.create is intentional for subclass support\n const sign1 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n signature: options.signature ?? new Uint8Array(),\n })\n\n sign1.externalAad = options.externalAad\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 { cborDecode } from '../cbor'\nimport type { CoseKey } from './key'\nimport { Mac0, type Mac0Context, type Mac0Options } from './mac0'\nimport { Sign1, type Sign1Context, type Sign1Options } from './sign1'\n\nexport type CwtOptions = Sign1Options | Mac0Options\n\nexport class Cwt {\n public constructor(private options: CwtOptions) {}\n\n public static create(options: CwtOptions) {\n return new Cwt(options)\n }\n\n public static fromToken(token: Uint8Array) {\n const decoded = cborDecode<Sign1 | Mac0>(token)\n return new Cwt(decoded)\n }\n\n public get asSign1() {\n return Sign1.create(this.options)\n }\n\n public get asMac0() {\n return Mac0.create(this.options)\n }\n\n public get payload() {\n return this.options.payload\n }\n\n public get protectedHeaders() {\n return this.options.protectedHeaders\n }\n\n public get unprotectedHeaders() {\n return this.options.unprotectedHeaders\n }\n\n public get signatureOrTag() {\n return 'signature' in this.options ? this.options.signature : 'tag' in this.options ? this.options.tag : undefined\n }\n\n public async verifySignature({ key }: { key: CoseKey }, ctx: Pick<Sign1Context, 'verify'>) {\n return await this.asSign1.verifySignature({ key }, ctx)\n }\n\n public async verifyAuthenticationCode({ key }: { key: CoseKey }, ctx: Pick<Mac0Context, 'verify'>) {\n return await this.asMac0.verifyAuthenticationCode({ key }, ctx)\n }\n}\n"],"mappings":";;;;;AAGA,EAAE,OAAO,EACP,aAAa,eAAe,EAC9B,CAAC;AAED,SAAS,eAAe,OAA4B;CAClD,IAAI,CAAC,OAAO,OAAO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,"file":"index.mjs","names":["#data","#buffer","addExtension","z","addExtension","addExtension","z","z","z","addExtension"],"sources":["../src/utils/zod-error.ts","../src/utils/zod.ts","../src/cbor/parser.ts","../src/cbor/data-item.ts","../src/cbor/cbor-structure.ts","../src/cbor/models/date.ts","../src/cbor/models/date-only.ts","../src/cose/claims/default.ts","../src/cose/error.ts","../src/cose/headers/defaults.ts","../src/utils/typed-map.ts","../src/cose/headers/header-claims.ts","../src/cose/headers/protected-headers.ts","../src/cose/headers/unprotected-headers.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 { Encoder, type Options } from 'cbor-x'\nimport { DataItem } from './data-item'\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 const decoded = enc.decode(input)\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 return Uint8Array.from(enc.encode(obj))\n}\n","import { addExtension } from 'cbor-x'\nimport z from 'zod'\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 { Tag } from 'cbor-x'\nimport { z } from 'zod'\nimport {\n decodeStructureWithErrorHandling,\n encodeStructureWithErrorHandling,\n parseStructureWithErrorHandling,\n} from '../utils/zod'\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 { 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","/**\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","// biome-ignore format: no explanation\nclass CoseError extends Error {\n constructor(message: string = new.target.name) {\n super(message)\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 {}\nexport class CoseKeyTypeNotSupportedForPrivateKeyExtractionError extends CoseError {}\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 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 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 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 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 return this.map.delete(key)\n }\n\n clear(): void {\n this.map.clear()\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\ntype 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\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 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 * 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 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 '${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 '${key}' to be defined.`,\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\n path: [`${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","import z from 'zod'\nimport { type TypedMap, typedMap } 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 * Schema for the known COSE header claims (RFC 9052 Section 3.1 / RFC 9360 / the IANA COSE Header\n * Parameters registry). Shared by the protected and unprotected header 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(\n [\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 [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 { allowAdditionalKeys: true }\n)\n\nexport type CoseHeaderClaims = z.infer<typeof coseHeaderClaimsSchema>\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 * e.g. a status list's `typ`). The typed claims are still validated at decode by\n * `coseHeaderClaimsSchema`; this view only governs typed access.\n */\nexport type CoseHeaders = OpenIntegerKeys<CoseHeaderClaims>\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport { cborDecode, cborEncode } from '../../cbor/parser.js'\nimport { 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\nexport type ProtectedHeaderOptions = {\n protectedHeaders?: Map<number, unknown>\n}\n\nexport class ProtectedHeaders extends CborStructure<\n ProtectedHeadersEncodedStructure,\n ProtectedHeadersDecodedStructure\n> {\n public static override get encodingSchema() {\n return z.codec(protectedHeadersEncodedStructure, coseHeaderClaimsSchema.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.toMap()) as Uint8Array<ArrayBuffer>,\n decode: (encoded) => TypedMap.fromMap(cborDecode(encoded) as Map<number, unknown>),\n })\n }\n\n public get headers(): CoseHeaders {\n return this.structure as unknown as CoseHeaders\n }\n\n public static create(options: ProtectedHeaderOptions) {\n return ProtectedHeaders.fromDecodedStructure(TypedMap.fromMap(options.protectedHeaders ?? new Map()))\n }\n}\n","import z from 'zod'\nimport { CborStructure } from '../../cbor/cbor-structure.js'\nimport { 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\nexport class UnprotectedHeaders extends CborStructure<\n UnprotectedHeadersEncodedStructure,\n UnprotectedHeadersDecodedStructure\n> {\n public static override get encodingSchema() {\n return coseHeaderClaimsSchema\n }\n\n public get headers(): CoseHeaders {\n return this.structure as unknown as CoseHeaders\n }\n\n public static create(options: UnprotectedHeaderOptions) {\n return UnprotectedHeaders.fromDecodedStructure(TypedMap.fromMap(options.unprotectedHeaders ?? new Map()))\n }\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 [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\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 externalAad?: Uint8Array\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 externalAad?: Uint8Array\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 */\n public toBeAuthenticated(options?: { detachedPayload?: 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: this.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 // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\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 rawStructure instanceof Mac0\n ? rawStructure.decodedStructure\n : Mac0.fromEncodedStructure(rawStructure as EncodedStructureType<T>).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 // biome-ignore lint/complexity/noThisInStatic: this.create is intentional for subclass support\n const mac0 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n tag: options.tag ?? new Uint8Array(),\n })\n\n mac0.externalAad = options.externalAad\n\n return mac0\n }\n\n public async authenticate(\n options: {\n key: CoseKey | Uint8Array\n detachedPayload?: Uint8Array\n algorithm?: MacAlgorithm\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: this.externalAad,\n }),\n algorithm: macAlgorithm,\n key: options.key,\n })\n return this\n }\n\n public async verifyAuthenticationCode(\n { key, detachedPayload }: { key: CoseKey; detachedPayload?: 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 }),\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 { addExtension } from 'cbor-x'\nimport z from 'zod'\nimport {\n type AnyCborStructure,\n CborStructure,\n type CborStructureStaticThis,\n cborDecode,\n cborEncode,\n type EncodedStructureType,\n} from '../cbor'\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 externalAad?: Uint8Array\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 externalAad?: Uint8Array\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 */\n public toBeSigned(options?: { detachedPayload?: 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: this.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 // biome-ignore lint/complexity/noThisInStatic: this.decode is intentional for subclass support\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 rawStructure instanceof Sign1\n ? rawStructure.decodedStructure\n : Sign1.fromEncodedStructure(rawStructure as EncodedStructureType<T>).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 }: { key: CoseKey; detachedPayload?: 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 }),\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 // biome-ignore lint/complexity/noThisInStatic: this.create is intentional for subclass support\n const sign1 = new this({\n protectedHeaders,\n unprotectedHeaders,\n payload: options.payload,\n signature: options.signature ?? new Uint8Array(),\n })\n\n sign1.externalAad = options.externalAad\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 { cborDecode } from '../cbor'\nimport type { CoseKey } from './key'\nimport { Mac0, type Mac0Context, type Mac0Options } from './mac0'\nimport { Sign1, type Sign1Context, type Sign1Options } from './sign1'\n\nexport type CwtOptions = Sign1Options | Mac0Options\n\nexport class Cwt {\n public constructor(private options: CwtOptions) {}\n\n public static create(options: CwtOptions) {\n return new Cwt(options)\n }\n\n public static fromToken(token: Uint8Array) {\n const decoded = cborDecode<Sign1 | Mac0>(token)\n return new Cwt(decoded)\n }\n\n public get asSign1() {\n return Sign1.create(this.options)\n }\n\n public get asMac0() {\n return Mac0.create(this.options)\n }\n\n public get payload() {\n return this.options.payload\n }\n\n public get protectedHeaders() {\n return this.options.protectedHeaders\n }\n\n public get unprotectedHeaders() {\n return this.options.unprotectedHeaders\n }\n\n public get signatureOrTag() {\n return 'signature' in this.options ? this.options.signature : 'tag' in this.options ? this.options.tag : undefined\n }\n\n public async verifySignature({ key }: { key: CoseKey }, ctx: Pick<Sign1Context, 'verify'>) {\n return await this.asSign1.verifySignature({ key }, ctx)\n }\n\n public async verifyAuthenticationCode({ key }: { key: CoseKey }, ctx: Pick<Mac0Context, 'verify'>) {\n return await this.asMac0.verifyAuthenticationCode({ key }, ctx)\n }\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+C,UAAU;AAKtF,SAAgB,gCACd,eACA,QACA,MACA,oBACiB;CACjB,MAAM,cAAc,EAAE,UAAU,QAAQ,IAAI;CAE5C,IAAI,CAAC,YAAY,SACf,MAAM,IAAI,gBAAgB,sBAAsB,kBAAkB,iBAAiB,YAAY,KAAK;CAGtG,OAAO,YAAY;AACrB;AAEA,SAAgB,iCACd,eACA,QACA,MACA,oBACiB;CACjB,MAAM,eAAe,EAAE,WAAW,QAAQ,IAAI;CAE9C,IAAI,CAAC,aAAa,SAChB,MAAM,IAAI,gBAAgB,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,UAAU;EACnB,OAAO,KAAK,QAAQ;CACtB;CAEA,IAAW,mBAAmB;EAC5B,OAAO,KAAK,QAAQ;CACtB;CAEA,IAAW,qBAAqB;EAC9B,OAAO,KAAK,QAAQ;CACtB;CAEA,IAAW,iBAAiB;EAC1B,OAAO,eAAe,KAAK,UAAU,KAAK,QAAQ,YAAY,SAAS,KAAK,UAAU,KAAK,QAAQ,MAAM,KAAA;CAC3G;CAEA,MAAa,gBAAgB,EAAE,OAAyB,KAAmC;EACzF,OAAO,MAAM,KAAK,QAAQ,gBAAgB,EAAE,IAAI,GAAG,GAAG;CACxD;CAEA,MAAa,yBAAyB,EAAE,OAAyB,KAAkC;EACjG,OAAO,MAAM,KAAK,OAAO,yBAAyB,EAAE,IAAI,GAAG,GAAG;CAChE;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@owf/cose",
|
|
3
|
-
"version": "0.3.2-alpha-
|
|
3
|
+
"version": "0.3.2-alpha-20260713153517",
|
|
4
4
|
"files": [
|
|
5
5
|
"dist"
|
|
6
6
|
],
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"cbor-x": "^1.6.4",
|
|
31
31
|
"zod": "^4.4.3",
|
|
32
32
|
"zod-validation-error": "^5.0.0",
|
|
33
|
-
"@owf/identity-common": "0.3.2-alpha-
|
|
33
|
+
"@owf/identity-common": "0.3.2-alpha-20260713153517"
|
|
34
34
|
},
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@noble/curves": "^2.0.1",
|