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:

Terminal:

```bash
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-cose.ts:

```ts
// 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:

Terminal:

```bash
npx tsx sign-cose.ts
```

Output:

```text
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`](https://github.com/yourbuddyconner/toip-tools/blob/main/site/examples/guides/sign-cose.ts).

## How it works

- `encodeCbor` writes RFC 8949 Core Deterministic Encoding, so the same value always gives the same bytes. `decodeCbor` insists on that form by default.
- `seedSigner` signs with Ed25519 from a 32-byte seed (algorithm `-19`). `webCryptoSigner` wraps a WebCrypto key pair; generated with `extractable: false`, the private key never leaves WebCrypto. A P-256 key signs as ESP256 (`-9`) unless you ask for ES256 (`-7`).
- `verifyCose1` takes a `KeyLookup`: 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 `allowedAlgs` list, and use the payload only when `result.ok` is true. Failures are values: `malformed`, `algNotAllowed`, `keyMismatch`, `signatureInvalid` and the WebAuthn checks.

## Limits and production notes

- Detached payloads and critical headers are refused as malformed.
- `webAuthnSigner` signs with a passkey (algorithm `-65600`); verify those messages with an explicit `webauthnOrigins` list.
- The tests reproduce the COSE working group's Ed25519 example byte for byte and verify RFC 9052's ES256 example.

## Related

### API used

[`signCose1`](https://toip.tools/toolkit/cose/api/signCose1/) · [`verifyCose1`](https://toip.tools/toolkit/cose/api/verifyCose1/) · [`seedSigner`](https://toip.tools/toolkit/cose/api/seedSigner/) · [`webCryptoSigner`](https://toip.tools/toolkit/cose/api/webCryptoSigner/) · [`encodeCbor`](https://toip.tools/toolkit/cose/api/encodeCbor/) · [`decodeCbor`](https://toip.tools/toolkit/cose/api/decodeCbor/) · [`KeyLookup`](https://toip.tools/toolkit/cose/api/KeyLookup/) · [`ALG`](https://toip.tools/toolkit/cose/api/ALG/) · [`webAuthnSigner`](https://toip.tools/toolkit/cose/api/webAuthnSigner/)

### Libraries

- [`@toip-tools/cose`](https://toip.tools/toolkit/cose/): Deterministic CBOR and COSE\_Sign1, with Ed25519, P-256, WebCrypto and passkey signers.

### Concepts

- [Decentralized identifiers](https://toip.tools/concepts/#dids)

### More guides

- [Send Trust Tasks over LoRa radio](https://toip.tools/guides/trust-tasks-over-lora/)
- [Create a did:key and sign a JSON document in TypeScript](https://toip.tools/guides/did-key-sign-document/)

---

This is the Markdown version of https://toip.tools/guides/sign-cose/. An index of the documentation for AI assistants is at https://toip.tools/llms.txt.
