Guide ยท @toip-tools/cose
Sign and verify COSE messages in TypeScript
Sign COSE_Sign1 messages over deterministic CBOR with Ed25519 or a non-extractable WebCrypto P-256 key, and verify them against trusted keys.
COSE (CBOR Object Signing and Encryption, RFC 9052) is the compact, binary counterpart of JOSE. A COSE_Sign1 message is a few dozen bytes plus its payload, which suits sensors, radio links, QR codes and anything else where bytes count.
This program signs one sensor reading with two kinds of key, verifies both against a table of trusted keys, then shows a tampered message and a signature by an untrusted key both failing.
Before you start
You need Node 22.13 or later. In a new folder, install the package and tsx, a TypeScript runner:
mkdir sign-cose && cd sign-cose
npm init -y && npm pkg set type=module
npm install @toip-tools/cose tsx
The code
Save this as sign-cose.ts. It is the complete program; the site's checks run it on every build.
// Sign and verify COSE_Sign1 messages (RFC 9052) over deterministic CBOR, with an Ed25519 seed and with a
// non-extractable P-256 WebCrypto key. Runs in Node and in browsers.
import { ALG, decodeCbor, encodeCbor, seedSigner, signCose1, verifyCose1, webCryptoSigner, type KeyLookup, type PublicKey } from "@toip-tools/cose";
const kid = (s: string) => new TextEncoder().encode(s);
// Two signers: an Ed25519 key from a 32-byte seed, and a P-256 key that WebCrypto never lets you export.
const sensor = seedSigner(crypto.getRandomValues(new Uint8Array(32)), kid("sensor-7"));
const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]);
const gateway = await webCryptoSigner(pair, kid("gateway-1"));
console.log("Algorithms:", sensor.alg, "(Ed25519),", gateway.alg, "(ESP256)");
// The payload is CBOR: compact and deterministic, so the same reading always encodes to the same bytes.
const reading = encodeCbor({ v: 1, kind: "temp", milliC: 21_375, at: 1_762_416_000 });
const fromSensor = await signCose1(reading, sensor, { contentType: "application/cbor" });
const fromGateway = await signCose1(reading, gateway, { contentType: "application/cbor" });
console.log("Message sizes:", fromSensor.length, "and", fromGateway.length, "bytes");
// The verifier decides which keys it trusts. The kid in the message is only a hint for finding one.
const trusted = new Map<string, PublicKey>([["sensor-7", sensor.publicKey], ["gateway-1", gateway.publicKey]]);
const lookup: KeyLookup = async (id) => {
const key = id && trusted.get(new TextDecoder().decode(id));
return key ? [key] : [];
};
const allowedAlgs = [ALG.Ed25519, ALG.ESP256, ALG.ES256];
for (const [who, msg] of [["sensor", fromSensor], ["gateway", fromGateway]] as const) {
const r = await verifyCose1(msg, lookup, { allowedAlgs });
console.log(`From the ${who}:`, r.ok ? decodeCbor(r.value.payload) : r.failure);
}
// One flipped bit in the payload, and verification fails. Use the payload only when ok is true.
const tampered = fromSensor.slice();
tampered[tampered.length - 70] ^= 0x01;
const r = await verifyCose1(tampered, lookup, { allowedAlgs });
console.log("Tampered:", r.ok ? "verified" : r.failure);
// A message signed by a key you don't trust fails too, whatever kid it claims.
const stranger = seedSigner(crypto.getRandomValues(new Uint8Array(32)), kid("sensor-7"));
const spoofed = await verifyCose1(await signCose1(reading, stranger), lookup, { allowedAlgs });
console.log("Signed by an unknown key claiming sensor-7:", spoofed.ok ? "verified" : spoofed.failure);
Run it:
npx tsx sign-cose.ts
Algorithms: -19 (Ed25519), -9 (ESP256)
Message sizes: 136 and 137 bytes
From the sensor: { v: 1, at: 1762416000, kind: 'temp', milliC: 21375 }
From the gateway: { v: 1, at: 1762416000, kind: 'temp', milliC: 21375 }
Tampered: signatureInvalid
Signed by an unknown key claiming sensor-7: signatureInvalid
Keys are random, so identifiers and sizes differ on each run. From a clone of the repository, run npx tsx --tsconfig site/tsconfig.json site/examples/guides/sign-cose.ts, or read it in site/examples/guides/sign-cose.ts.
How it works
encodeCborwrites RFC 8949 Core Deterministic Encoding, so the same value always gives the same bytes.decodeCborinsists on that form by default.seedSignersigns with Ed25519 from a 32-byte seed (algorithm-19).webCryptoSignerwraps a WebCrypto key pair; generated withextractable: false, the private key never leaves WebCrypto. A P-256 key signs as ESP256 (-9) unless you ask for ES256 (-7).verifyCose1takes aKeyLookup: you map the message's key ID to keys you already trust. The key ID is only a hint; a message signed by any other key fails.- Pass an explicit
allowedAlgslist, and use the payload only whenresult.okis true. Failures are values:malformed,algNotAllowed,keyMismatch,signatureInvalidand the WebAuthn checks.
Limits and production notes
- Detached payloads and critical headers are refused as malformed.
webAuthnSignersigns with a passkey (algorithm-65600); verify those messages with an explicitwebauthnOriginslist.- The tests reproduce the COSE working group's Ed25519 example byte for byte and verify RFC 9052's ES256 example.