Skip to content

Commit

Permalink
fix: guard SignJWT.prototype.sign() from missing protected header
Browse files Browse the repository at this point in the history
fixes #221
  • Loading branch information
panva committed Jul 1, 2021
1 parent 72a72db commit 4103719
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/jwt/sign.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class SignJWT extends ProduceJWT {
async sign(key: KeyLike, options?: SignOptions): Promise<string> {
const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)))
sig.setProtectedHeader(this._protectedHeader)
if (this._protectedHeader.crit?.includes('b64') && this._protectedHeader.b64 === false) {
if (this._protectedHeader?.crit?.includes('b64') && this._protectedHeader.b64 === false) {
throw new JWTInvalid('JWTs MUST NOT use unencoded payload')
}
return sig.sign(key, options)
Expand Down
6 changes: 6 additions & 0 deletions test/jwt/sign.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ Promise.all([
.sign(t.context.secret),
{ code: 'ERR_JWT_INVALID', message: 'JWTs MUST NOT use unencoded payload' },
);
await t.throwsAsync(
() =>
new SignJWT({})
.sign(t.context.secret),
{ code: 'ERR_JWS_INVALID', message: 'either setProtectedHeader or setUnprotectedHeader must be called before #sign()' },
);
});

async function testJWTsetFunction(t, method, claim, value, expected = value) {
Expand Down

0 comments on commit 4103719

Please sign in to comment.