From b9de5af4a4da03d4561cb95490a466f302ae8fd6 Mon Sep 17 00:00:00 2001 From: Vladimir Dementyev Date: Tue, 24 Oct 2023 19:42:48 -0700 Subject: [PATCH] + handle jwt expiration within application --- src/application/index.ts | 22 +++++++++++++++++----- tests/application.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/src/application/index.ts b/src/application/index.ts index d67d41b..5461962 100644 --- a/src/application/index.ts +++ b/src/application/index.ts @@ -117,12 +117,24 @@ export class Application { } async handleOpen(handle: ConnectionHandle) { - await this.connect(handle) + try { + await this.connect(handle) - if (handle.rejected) { - handle.transmit({ type: 'disconnect', reason: 'unauthorized' }) - } else { - handle.transmit({ type: 'welcome', sid: handle.id }) + if (handle.rejected) { + handle.transmit({ type: 'disconnect', reason: 'unauthorized' }) + } else { + handle.transmit({ type: 'welcome', sid: handle.id }) + } + } catch (e) { + if ((e as any)?.code == 'ERR_JWT_EXPIRED') { + handle.reject().transmit({ + type: 'disconnect', + reason: 'token_expired', + reconnect: false + }) + } else { + throw e + } } } diff --git a/tests/application.test.ts b/tests/application.test.ts index 2ec80ce..eb5a922 100644 --- a/tests/application.test.ts +++ b/tests/application.test.ts @@ -1,3 +1,4 @@ +import { errors } from 'jose' import { Application, ConnectionHandle, @@ -59,6 +60,30 @@ ApplicationTest('handleOpen when unauthorized', async () => { ]) }) +ApplicationTest('handleOpen when token expired', async () => { + const app = new TestApplication() + + const handle = new ConnectionHandle('123', { + url: 'http://localhost?user_id=1&token=expired' + }) + + app.connect = async (handle: ConnectionHandle) => { + throw new errors.JWTExpired('expired') + } + + await app.handleOpen(handle) + + assert.is(handle.rejected, true) + assert.is(handle.transmissions.length, 1) + + const transmission = JSON.parse(handle.transmissions[0]) + assert.equal(transmission, { + type: 'disconnect', + reason: 'token_expired', + reconnect: false + }) +}) + ApplicationTest('handleClose', async () => { const app = new TestApplication()