diff --git a/library/helpers/tryDecodeAsJWT.test.ts b/library/helpers/tryDecodeAsJWT.test.ts index d32e8d188..bed5fe0db 100644 --- a/library/helpers/tryDecodeAsJWT.test.ts +++ b/library/helpers/tryDecodeAsJWT.test.ts @@ -16,13 +16,13 @@ t.test("it returns payload for invalid JWT", async () => { // According to the JWT spec, the payload is not valid, but we'll extract the payload anyway // e30= is a base64 encoded string of '{}' - t.same(tryDecodeAsJWT("/;ping%20localhost;.e30=."), { + t.same(tryDecodeAsJWT("/;ping%20localhost---;.e30=."), { jwt: true, object: {}, }); // W10= is a base64 encoded string of '[]' - t.same(tryDecodeAsJWT("/;ping%20localhost;.W10=."), { + t.same(tryDecodeAsJWT("/;ping%20localhost---;.W10=."), { jwt: true, object: [], }); @@ -66,3 +66,18 @@ t.test( ); } ); + +t.test("it ignores jwts shorter than possible", async (t) => { + t.same(tryDecodeAsJWT("a.a.a"), { jwt: false }); + t.same(tryDecodeAsJWT("aaaaaaaa.eyJhIjoxfQ==.aaa"), { jwt: false }); + t.same(tryDecodeAsJWT("aaaaaaaa.eyJhIjoxfQ==.aaaaaaaaa"), { + jwt: true, + object: { a: 1 }, + }); +}); + +t.test("invalid json", async (t) => { + t.same(tryDecodeAsJWT("aaaaaaaa.einvalidyJhIjoxfQ==.aaaa"), { + jwt: false, + }); +}); diff --git a/library/helpers/tryDecodeAsJWT.ts b/library/helpers/tryDecodeAsJWT.ts index 463e08d5f..f6f577c27 100644 --- a/library/helpers/tryDecodeAsJWT.ts +++ b/library/helpers/tryDecodeAsJWT.ts @@ -8,7 +8,9 @@ export function tryDecodeAsJWT( jwt: string ): { jwt: true; object: unknown } | { jwt: false } { - if (!jwt.includes(".")) { + // The minimum JWT length is 26 characters + // See https://datatracker.ietf.org/doc/html/rfc7519#section-6.1 + if (jwt.length < 26 || !jwt.includes(".")) { return { jwt: false }; }