SDK library · Browser and Node

# cose

Encode deterministic CBOR and sign attached-payload COSE\_Sign1 messages with asynchronous Ed25519, P-256, WebCrypto, or WebAuthn signers. Verification returns a result union for malformed or cryptographically invalid messages.

`@toip-tools/cose` · v0.1.0 · [Source](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/cose/src/index.ts)

## Setup

Install the package from npm. It needs Node 22.13 or later, or a bundler for browser entry points.

Install:

```bash
npm install @toip-tools/cose
```

**Runtime:** Browsers and Node. The main entry has no Node-only imports.

Import:

```ts
import { encodeCbor, decodeCbor, Tagged } from "@toip-tools/cose";
```

## Usage

### Encode and decode deterministic CBOR

Pass plain objects to `encodeCbor` for text-key maps; use `Map` for integer or mixed keys and `Tagged` for CBOR tags. `decodeCbor` checks deterministic encoding by default. Set `useMaps: true` when every map must remain a `Map`; use `strict: false` only when your input contract accepts other well-formed CBOR encodings.

[`encodeCbor`](https://toip.tools/toolkit/cose/api/encodeCbor/) · [`decodeCbor`](https://toip.tools/toolkit/cose/api/decodeCbor/) · [`Tagged`](https://toip.tools/toolkit/cose/api/Tagged/) · [`DecodeCborOptions`](https://toip.tools/toolkit/cose/api/DecodeCborOptions/)

### Sign bytes and verify trusted candidate keys

Create `seedSigner(seed, kid)` or await `webCryptoSigner(pair, kid)`, then call `signCose1(payload, signer, options)`. At verification, supply an explicit algorithm allowlist and a `KeyLookup` that returns trusted keys for the `kid` and algorithm. Consume `result.value.payload` only when `result.ok` is true. If using `externalAad`, both sides must supply the same bytes.

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

### Use a passkey for signing

Construct `webAuthnSigner` with the registered credential ID, relying-party ID, public key, and key ID. Each signature requests a WebAuthn assertion with user verification. Verify algorithm `-65600` with an explicit `webauthnOrigins` allowlist; successful verification includes origin and authenticator flags in `value.webauthn`.

[`webAuthnSigner`](https://toip.tools/toolkit/cose/api/webAuthnSigner/) · [`verifyCose1`](https://toip.tools/toolkit/cose/api/verifyCose1/) · [`WebAuthnInfo`](https://toip.tools/toolkit/cose/api/WebAuthnInfo/) · [`ALG`](https://toip.tools/toolkit/cose/api/ALG/)

## Example

A sensor signs a reading as COSE\_Sign1 over deterministic CBOR; anyone with its key verifies it.

site/examples/snippets/cose.ts:

```ts
import { decodeCbor, encodeCbor, seedSigner, verifyCose1, signCose1 } from "@toip-tools/cose";

const seed = crypto.getRandomValues(new Uint8Array(32));
const sensor = seedSigner(seed, new TextEncoder().encode("sensor-7#0")); // alg -19, Ed25519

const reading = encodeCbor({ v: 1, kind: "temp", milliC: 21_375, at: 1_762_416_000 });
const signed = await signCose1(reading, sensor, { contentType: "application/cbor" });

const result = await verifyCose1(signed, async () => [sensor.publicKey], { allowedAlgs: [-19] });
if (result.ok) console.log("verified", decodeCbor(result.value.payload), `${signed.length} bytes`);
else console.log("refused:", result.failure);
```

Run from the repository root:

```bash
npx tsx --tsconfig site/tsconfig.json site/examples/snippets/cose.ts
```

Output:

```text
verified { v: 1, at: 1762416000, kind: 'temp', milliC: 21375 } 138 bytes
```

## Lifecycle and persistence

- The package does not persist keys or provide a signer disposal method. Own seed storage, WebCrypto key persistence, and the trusted mapping from key IDs to public keys. A key ID is a lookup hint, not a trust decision.

- Keep external AAD alongside the protocol context needed to reproduce it; it is bound into the signature but not transmitted in the COSE message. Detached payloads and critical headers are unsupported.

## Error handling

### `malformed / algNotAllowed`

`verifyCose1` returns `ok: false` for bad COSE structure, unsupported critical headers or detached payloads, and algorithms outside the supported or configured set.

Reject the message. Update an allowlist only after deciding that the algorithm is permitted by your protocol.

### `keyMismatch / signatureInvalid`

`keyMismatch` means lookup produced no key of the required curve; `signatureInvalid` means no suitable candidate verified.

Check trusted key history and key ID mapping. Verify AAD agreement; never accept the payload merely because it decoded.

### `webauthnChallenge / webauthnOrigin / webauthnFlags`

Passkey verification fails if the challenge/type, allowed origin or RP hash, or required user-presence/user-verification flags do not match.

Correct registration and origin configuration or obtain a fresh assertion. Keep origin checks enabled. Catch WebAuthn prompt failures and `KeyLookup` exceptions separately; those can reject the promise.

### `CBOR decoding exception`

Strict `decodeCbor` throws for noncanonical encoding, duplicate or unordered keys, invalid UTF-8, unsupported values, and trailing bytes.

Catch decoding exceptions at input boundaries. Relax strictness only when the surrounding format allows it.

### Limitations

- Detached payloads and critical headers. They are refused as malformed.

## API reference

Choose an entry point for the complete export list. Each export has a reference page with its signature, parameter types, return type, fields, and public methods where applicable.

- [`@toip-tools/cose`](https://toip.tools/toolkit/cose/api/)

  Browser and Node · 24 exports

## Related

### Guides

- [Sign and verify COSE messages in TypeScript](https://toip.tools/guides/sign-cose/)

### Used by these examples

- [Capture](https://toip.tools/examples/#capture): Verifiable origins for photos and sensor readings.
- [Mesh](https://toip.tools/examples/#mesh): Trust Tasks beyond an internet connection.

### Concepts

[Concepts](https://toip.tools/concepts/) explains the protocols behind cose; the [FAQ](https://toip.tools/faq/) covers install, runtimes and support.

---

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