toip.tools

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/cosev0.1.0Source

Setup

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

ShellInstall
npm install @toip-tools/cose

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

TypeScriptImport
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.

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.

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.

Example

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

TypeScriptsite/examples/snippets/cose.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);
ShellRun from the repository root
npx tsx --tsconfig site/tsconfig.json site/examples/snippets/cose.ts
OutputRecorded output
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.