Skip to content

Commit 9c2b76c

Browse files
authored
fix: Middleware should not throw ERR_JWE_INVALID (#2546)
2 parents d1fe0b8 + 41267a7 commit 9c2b76c

3 files changed

Lines changed: 19 additions & 2 deletions

File tree

src/server/cookies.test.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,20 @@ describe("encrypt/decrypt", async () => {
4343
expect(decrypted).toBeNull();
4444
});
4545

46+
it("should fail to decrypt a tampered payload", async () => {
47+
const payload = { key: "value" };
48+
const maxAge = 60 * 60; // 1 hour in seconds
49+
const expiration = Math.floor(Date.now() / 1000 + maxAge);
50+
const encrypted = await encrypt(payload, secret, expiration);
51+
52+
// Tamper with the encrypted payload by shifting the first character
53+
const tampered =
54+
String.fromCharCode(encrypted.charCodeAt(0) + 1) + encrypted.slice(1);
55+
56+
const decrypted = await decrypt(tampered, secret);
57+
expect(decrypted).toBeNull();
58+
});
59+
4660
it("should fail to encrypt if a secret is not provided", async () => {
4761
const payload = { key: "value" };
4862
const maxAge = 60 * 60; // 1 hour in seconds

src/server/cookies.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,8 @@ export async function decrypt<T>(
6868
// When the JWE can not be decrypted or has expired, return null to indicate an invalid cookie and treat it as non-existent.
6969
if (
7070
e.code === "ERR_JWE_DECRYPTION_FAILED" ||
71-
e.code === "ERR_JWT_EXPIRED"
71+
e.code === "ERR_JWT_EXPIRED" ||
72+
e.code === "ERR_JWE_INVALID"
7273
) {
7374
return null;
7475
}

src/server/session/stateful-session-store.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ export class StatefulSessionStore extends AbstractSessionStore {
7474
try {
7575
const sessionCookie = await cookies.decrypt<SessionCookieValue>(
7676
cookie.value,
77-
this.secret
77+
this.secret,
78+
undefined,
79+
true // throwOnJWEErrors: allow catching ERR_JWE_INVALID to handle legacy sessions
7880
);
7981

8082
if (sessionCookie === null) {

0 commit comments

Comments
 (0)