UNPKG

cose-kit

Version:

This is an early prototype of a RFC8152 COSE library for node.js.

90 lines (89 loc) 3.44 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Sign1 = void 0; const verify_js_1 = __importDefault(require("#runtime/verify.js")); const headers_js_1 = require("../headers.js"); const sign_js_1 = __importDefault(require("#runtime/sign.js")); const buffer_utils_js_1 = require("../lib/buffer_utils.js"); const SignatureBase_js_1 = require("./SignatureBase.js"); const cbor_js_1 = require("../cbor.js"); class Sign1 extends SignatureBase_js_1.SignatureBase { constructor(protectedHeaders, unprotectedHeaders, payload, signature) { super(protectedHeaders, unprotectedHeaders, signature); this.payload = payload; } getContentForEncoding() { return [ this.encodedProtectedHeaders, this.unprotectedHeaders, this.payload, this.signature, ]; } encode() { return cbor_js_1.encoder.encode(this); } static Signature1(protectedHeaders, applicationHeaders, payload) { return cbor_js_1.encoder.encode([ 'Signature1', protectedHeaders, applicationHeaders, payload, ]); } async verify(key, externalAAD = new Uint8Array()) { if (typeof key === 'function') { key = await key(this); } if (!key) { throw new Error('key not found'); } const toBeSigned = Sign1.Signature1(this.encodedProtectedHeaders || new Uint8Array(), externalAAD, this.payload); if (!this.algName) { throw new Error('unknown algorithm: ' + this.alg); } return (0, verify_js_1.default)(this.algName, key, this.signature, toBeSigned); } async verifyX509(roots) { const { publicKey } = await this.verifyX509Chain(roots); return this.verify(publicKey); } static async sign(protectedHeaders, unprotectedHeaders, payload, key) { const { alg } = protectedHeaders; const encodedProtectedHeaders = cbor_js_1.encoder.encode(new Map(Object.entries(protectedHeaders).map(([k, v]) => { if (k === 'alg') { v = headers_js_1.algsToValue.get(v); } else if (typeof v === 'string') { v = (0, buffer_utils_js_1.fromUTF8)(v); } return [headers_js_1.headers[k], v]; }))); const unprotectedHeadersMap = new Map(Object.entries(unprotectedHeaders || {}).map(([k, v]) => { if (typeof v === 'string') { v = (0, buffer_utils_js_1.fromUTF8)(v); } return [headers_js_1.headers[k], v]; })); const toBeSigned = Sign1.Signature1(encodedProtectedHeaders, new Uint8Array(), payload); if (!alg) { throw new Error('The alg header must be set.'); } const signature = await (0, sign_js_1.default)(alg, key, toBeSigned); return new Sign1(encodedProtectedHeaders, unprotectedHeadersMap, payload, signature); } } exports.Sign1 = Sign1; (0, cbor_js_1.addExtension)({ Class: Sign1, tag: 18, encode(instance, encodeFn) { return encodeFn(instance.getContentForEncoding()); }, decode: (data) => { return new Sign1(data[0], data[1], data[2], data[3]); } });