The package is ESM-only and requires Node.js 20.19+ or a modern browser runtime.
Import from subpath modules such as @ldclabs/cose-ts/sign1; the package root
is not a barrel entry point.
AI Agent Guide
If you are using an AI coding agent, start with AGENTS.md and
docs/agent-guide.md. The short contract is: choose the
COSE structure first, import from a package subpath, keep externalData
identical across encode/decode paths, and run pnpm run examples when snippets
or public APIs change.
COSE defines compact CBOR structures for signatures, encryption, MACs, keys,
and key sets. This library implements the RFC 9052 structures and common RFC
9053 algorithms in TypeScript.
KDF and key agreement helpers: HKDF-SHA and ECDH curves P-256, P-384, P-521,
X25519.
Quick Start
Sign and Verify with COSE_Sign1
import { Ed25519Key } from '@ldclabs/cose-ts/ed25519'import { Sign1Message } from '@ldclabs/cose-ts/sign1'import { utf8ToBytes } from '@ldclabs/cose-ts/utils'const privateKey = Ed25519Key.generate()const publicKey = privateKey.public()const signed = new Sign1Message(utf8ToBytes('hello')).toBytes(privateKey)const verified = Sign1Message.fromBytes(publicKey, signed)console.log(new TextDecoder().decode(verified.payload)) // "hello"
Encrypt with an Implicit Key
Use COSE_Encrypt0 when sender and receiver already know the content
encryption key.
import { AesGcmKey } from '@ldclabs/cose-ts/aesgcm'import { Encrypt0Message } from '@ldclabs/cose-ts/encrypt0'import * as iana from '@ldclabs/cose-ts/iana'import { utf8ToBytes } from '@ldclabs/cose-ts/utils'const key = AesGcmKey.generate(iana.AlgorithmA128GCM)const ciphertext = await new Encrypt0Message(utf8ToBytes('secret')).toBytes(key)const plaintext = await Encrypt0Message.fromBytes(key, ciphertext)console.log(new TextDecoder().decode(plaintext.payload)) // "secret"
Encrypt for Recipients with AES Key Wrap
Use COSE_Encrypt when the content encryption key needs to be carried for one
or more recipients. The content encryption key protects the payload; each
recipient key encryption key wraps that content key.
import * as iana from '@ldclabs/cose-ts/iana'import { AesKwKey } from '@ldclabs/cose-ts/aeskw'import { ChaCha20Poly1305Key } from '@ldclabs/cose-ts/chacha20poly1305'import { EncryptMessage } from '@ldclabs/cose-ts/encrypt'import { Recipient } from '@ldclabs/cose-ts/recipient'import { utf8ToBytes } from '@ldclabs/cose-ts/utils'const cek = ChaCha20Poly1305Key.generate()const kek = AesKwKey.generate(iana.AlgorithmA256KW, utf8ToBytes('kek-1'))const encrypted = await new EncryptMessage( utf8ToBytes('This is the content.'),
Create and Validate a CWT
import { Claims, Validator, withCWTTag } from '@ldclabs/cose-ts/cwt'import { Ed25519Key } from '@ldclabs/cose-ts/ed25519'import { Sign1Message } from '@ldclabs/cose-ts/sign1'import { randomBytes } from '@ldclabs/cose-ts/utils'const key = Ed25519Key.generate()const claims = new Claims()claims.iss = 'issuer'claims.aud = 'service'claims.sub = 'user-123'claims.exp = Math.floor(Date.now() / 1000) + 3600claims.cti = randomBytes(16)
Core Concepts
Headers
COSE headers are split into protected and unprotected buckets. Protected headers
are encoded as a byte string and are included in the signature, MAC, or AEAD
authenticated data. Unprotected headers are metadata only.
import * as iana from '@ldclabs/cose-ts/iana'import { Header } from '@ldclabs/cose-ts/header'const protectedHeader = new Header().setParam( iana.HeaderParameterContentType, 'application/cwt')
The library validates RFC 9052 header rules when encoding and decoding:
duplicate labels across header buckets are rejected, crit must be protected,
common header value types are checked, and IV and Partial IV cannot appear
in the same security layer. An alg header in either bucket must match the
key. The IV may be carried in either bucket; when none is set, the encryption
helpers generate one in the unprotected bucket. Partial IV is recognized but
not yet supported by the encryption helpers. Decoding also checks the COSE array
shape and element types before any cryptographic work.
External Authenticated Data
Every toBytes / fromBytes method for signatures, MACs, and AEAD encryption
accepts optional externalData. Pass the exact same bytes on verification or
decryption, or authentication will fail.
const aad = new TextEncoder().encode('coap-code-and-options')const signed = new Sign1Message(payload).toBytes(privateKey, aad)Sign1Message.fromBytes(publicKey, signed, aad)
Tags
Message classes accept tagged and untagged inputs. Use the static withTag
helpers when a protocol expects the standard COSE tag.
Keys are COSE_Key maps. generate() creates a fresh key, fromSecret() and
fromPublic() import raw key material, and public() removes private
parameters when available. fromSecret() also stores the derived public key,
and EC2 public keys are exported as uncompressed x/y coordinates. If a key
has a kid, message helpers copy it into the unprotected header as a
key-selection hint.
Key classes check the kty, alg, and crv of an imported COSE_Key and reject
a key of another type instead of rewriting it. ECDSAKey derives alg from
crv when the COSE_Key omits alg.
Use key_ops when a key should be restricted to a specific operation. The
operation is enforced by signing, verification, encryption, decryption, MAC, and
key-wrap helpers.
Module Guide
Use case
Import
Main exports
Single-signer signatures
@ldclabs/cose-ts/sign1
Sign1Message
Multi-signer signatures
@ldclabs/cose-ts/sign
SignMessage, Signature
Single-recipient encryption
@ldclabs/cose-ts/encrypt0
Encrypt0Message
Enveloped encryption
@ldclabs/cose-ts/encrypt
EncryptMessage
Single-key MAC
@ldclabs/cose-ts/mac0
Mac0Message
Recipient-based MAC
@ldclabs/cose-ts/mac
MacMessage
Recipients
Interoperability Notes
CBOR output uses deterministic RFC 8949 map ordering for integer and text
labels. Decoding rejects duplicate map keys.
Protected empty headers are encoded as a zero-length byte string, and decoding
accepts both the zero-length byte string and encoded empty-map forms.
COSE_recipient currently provides direct mode and AES-KW helpers. Unknown
recipient algorithms and nested recipients can be parsed, but key recovery is
only implemented for supported helpers and encode() rejects nested
recipients.
kid values are hints, not unique identifiers. Multi-key decoders try the
candidates whose kid matches first, then fall back to the others.
Text-string algorithm labels are accepted by generic header validation, but
built-in algorithms use the registered integer labels from iana.
Development
pnpm installpnpm run examplespnpm testpnpm run buildpnpm run test:distpnpm run lint
test:dist loads every built entry point through the package exports in plain
Node.js, without a bundler. Tests include RFC 9052 structure checks, RFC example vectors, runnable examples,
agent-oriented misuse checks, and coverage for encoding edge cases.
Security Notes
Always authenticate application context through externalData when protocol
metadata affects security decisions.
Reusing a nonce/IV with the same AEAD key is unsafe. Let the message helpers
generate IVs unless your protocol has its own nonce allocation scheme.
compareBytes is lexicographic and exits early; use equalBytes for
secret-derived values such as MAC tags.
This library does not choose algorithms or key-management policy for an
application profile. Protocols should specify which COSE structures,
algorithms, tags, and external authenticated data are required.