ts-jose
Version:
Wrap functions of JOSE in steady interface
51 lines • 1.86 kB
JavaScript
import { CompactSign, compactVerify, decodeProtectedHeader, EmbeddedJWK, } from 'jose';
import { JoseError } from './error.js';
export class JWS {
static async verify(signature, jwk, options) {
const key = await this.getKeyFrom(signature, jwk, options);
const result = (await (typeof key === 'function'
? compactVerify(signature, key, options)
: compactVerify(signature, key, options)));
if (options?.typ !== undefined &&
result.protectedHeader.typ !== options.typ) {
throw new JoseError('JWS', 'typ', options.typ);
}
return options?.complete
? {
payload: Buffer.from(result.payload).toString(),
header: result.protectedHeader,
key: result.key,
}
: Buffer.from(result.payload).toString();
}
static async sign(data, key, options) {
const jwk = key.getKey({
kid: options?.kid,
use: 'sig',
alg: options?.alg,
});
const encoder = new TextEncoder();
const jws = new CompactSign(encoder.encode(data));
jws.setProtectedHeader({
typ: options?.typ,
kid: options?.kid ?? jwk.kid,
alg: options?.alg ?? jwk.alg ?? '',
jwk: options?.jwk ? jwk.toObject() : undefined,
});
return jws.sign(jwk.key);
}
static async getKeyFrom(signature, key, options) {
if (key === undefined)
return EmbeddedJWK;
const header = decodeProtectedHeader(signature);
const publicKey = await key
.getKey({
use: 'sig',
kid: options?.kid ? options.kid : header.kid,
alg: header.alg,
})
.toPublic();
return publicKey.key;
}
}
//# sourceMappingURL=jws.js.map