cose-kit
Version:
This is an early prototype of a RFC8152 COSE library for node.js.
74 lines (73 loc) • 2.85 kB
JavaScript
import { KEY_TYPE, COSE_KEY_TYPE } from "./kty.js";
import { LABEL, BufferTypes, COSE_LABEL, KEY_TYPE_LABELS, COSE_KEY_TYPE_LABELS } from './labels.js';
import { encoder } from '../cbor.js';
import { importJWK } from 'jose';
import { COSE_CURVE, CURVE } from "./crv.js";
import { COSE_KEY_OPS, KEY_OPS } from './key_ops.js';
import { decodeBase64URL, encodeBase64URL } from '#runtime/base64.js';
import { ALG, COSE_ALG } from "./alg.js";
const toArray = (v) => Array.isArray(v) ? v : [v];
const parameterParsers = new Map([
['kty', (value) => KEY_TYPE.get(value)],
['crv', (value) => CURVE.get(value)],
['alg', (value) => ALG.get(value)],
['crit', (value) => {
const values = Array.isArray(value) ? value : [value];
return values.map(v => LABEL.get(v));
}],
['kid', (v) => v],
['key_ops', (v) => toArray(v).map((value) => KEY_OPS.get(value))],
...(BufferTypes.map((label) => [label, (v) => encodeBase64URL(v)]))
]);
function decodedCOSEKeyToJWK(decoded) {
var _a;
const result = {};
const kty = KEY_TYPE.get(decoded.get(COSE_LABEL.get('kty')));
for (const [key, value] of decoded) {
const jwkKey = LABEL.get(key) || (kty && ((_a = KEY_TYPE_LABELS[kty]) === null || _a === void 0 ? void 0 : _a.get(key)));
const parser = jwkKey && parameterParsers.get(jwkKey);
if (parser && jwkKey) {
result[jwkKey] = parser(value);
}
}
return result;
}
export function COSEKeyToJWK(coseKey) {
let decoded;
if (coseKey instanceof Uint8Array) {
decoded = encoder.decode(coseKey);
}
else {
decoded = coseKey;
}
const result = decodedCOSEKeyToJWK(decoded);
return result;
}
export async function importCOSEKey(coseKey) {
const jwk = coseKey instanceof Uint8Array ?
COSEKeyToJWK(coseKey) :
decodedCOSEKeyToJWK(coseKey);
return importJWK(jwk);
}
const parameterFormatter = new Map([
['kty', (value) => COSE_KEY_TYPE.get(value)],
['crv', (value) => COSE_CURVE.get(value)],
['alg', (value) => COSE_ALG.get(value)],
['crit', (value) => toArray(value).map(v => COSE_LABEL.get(v))],
['kid', (v) => v],
['key_ops', (v) => toArray(v).map((value) => COSE_KEY_OPS.get(value))],
...(BufferTypes.map((label) => [label, (v) => decodeBase64URL(v)]))
]);
export function COSEKeyFromJWK(jwk) {
var _a;
const coseKey = new Map();
const { kty } = jwk;
for (const [key, value] of Object.entries(jwk)) {
const coseKeyLabel = COSE_LABEL.get(key) || ((_a = COSE_KEY_TYPE_LABELS[kty]) === null || _a === void 0 ? void 0 : _a.get(key));
const formatter = parameterFormatter.get(key);
if (coseKeyLabel && formatter) {
coseKey.set(coseKeyLabel, formatter(value));
}
}
return encoder.encode(coseKey);
}