UNPKG

cose-kit

Version:

**DEPRECATED:** Use [@auth0/cose](https://www.npmjs.com/package/@auth0/cose).

98 lines (97 loc) 3.44 kB
import { JWKKeyType } from "./kty.js"; import { encoder } from '../cbor.js'; import { Curve } from "./curve.js"; import { TypedMap } from "@jfromaniello/typedmap"; import { Algorithms } from "../headers.js"; import { generateKeyPair, importJWK, exportJWK } from "jose"; import { COSEKeyParam, KTYSpecificJWKParamsRev, JWKParam, KTYSpecificJWKParams } from "./params.js"; import { JWKKeyOps, JWKKeyOpsToCOSE } from './key_ops.js'; import { decodeBase64URL, encodeBase64URL } from "#runtime/base64.js"; import { toBuffer } from "#runtime/buffer.js"; const toArray = (v) => Array.isArray(v) ? v : [v]; export const JWKFromCOSEValue = new Map([ ['kty', (value) => JWKKeyType[value]], ['crv', (value) => Curve[value]], ['alg', (value) => Algorithms[value]], ['kid', (v) => { if (typeof v === 'string') { return v; } return new TextDecoder().decode(v); }], ['key_ops', (v) => toArray(v).map((value) => JWKKeyOps.get(value))], ...([ 'x', 'y', 'd', 'k', ].map((param) => [param, (v) => encodeBase64URL(v)])) ]); export const JWKToCOSEValue = new Map([ ['kty', (value) => JWKKeyType[value]], ['crv', (value) => Curve[value]], ['alg', (value) => Algorithms[value]], ['kid', (v) => toBuffer(v)], ['key_ops', (v) => toArray(v).map((value) => JWKKeyOpsToCOSE.get(value)).flat()], ...([ 'x', 'y', 'd', 'k', ].map((label) => [label, (v) => decodeBase64URL(v)])) ]); export class COSEKey extends TypedMap { static import(data) { if (data instanceof Uint8Array) { const decoded = encoder.decode(data); return new COSEKey(decoded); } else { return new COSEKey(data); } } static fromJWK(jwk) { var _a; const coseKey = new COSEKey(); const kty = jwk.kty; for (const [key, value] of Object.entries(jwk)) { const jwkKey = ((_a = KTYSpecificJWKParamsRev[kty]) === null || _a === void 0 ? void 0 : _a.get(key)) || JWKParam[key]; const formatter = JWKToCOSEValue.get(key); if (jwkKey && formatter) { coseKey.set(jwkKey, formatter(value)); } } return coseKey; } static async generate(alg, options = {}) { const { privateKey, publicKey } = await generateKeyPair(Algorithms[alg], { ...options !== null && options !== void 0 ? options : {}, extractable: true }); return { privateKey: COSEKey.fromJWK(await exportJWK(privateKey)), publicKey: COSEKey.fromJWK(await exportJWK(publicKey)), }; } toJWK() { var _a, _b; const result = {}; const kty = JWKKeyType[this.get(COSEKeyParam.KeyType)]; for (const [key, value] of this) { const jwkKey = (_b = (_a = KTYSpecificJWKParams[kty]) === null || _a === void 0 ? void 0 : _a.get(key)) !== null && _b !== void 0 ? _b : JWKParam[key]; const parser = JWKFromCOSEValue.get(jwkKey); if (parser && jwkKey) { const parsed = parser(value); result[jwkKey] = parsed; } } return result; } toKeyLike() { return importJWK(this.toJWK()); } encode() { return encoder.encode(this.esMap); } }