2
1
mirror of https://github.com/Thream/socketio-jwt.git synced 2024-07-21 09:38:31 +02:00

fix: add better typings

This commit is contained in:
divlo 2020-12-29 00:53:45 +01:00
parent 638c86708e
commit 51a8a973c8
3 changed files with 184 additions and 140 deletions

View File

@ -46,7 +46,7 @@ describe('authorizer', () => {
test('auth headers are supported', (done) => { test('auth headers are supported', (done) => {
const socket = io.connect('http://localhost:9000', { const socket = io.connect('http://localhost:9000', {
// @ts-ignore // @ts-expect-error
extraHeaders: { Authorization: `Bearer ${token}` } extraHeaders: { Authorization: `Bearer ${token}` }
}) })
socket.on('connect', () => { socket.on('connect', () => {
@ -86,7 +86,7 @@ describe('authorizer', () => {
it('auth headers are supported', (done) => { it('auth headers are supported', (done) => {
const socket = io.connect('http://localhost:9000', { const socket = io.connect('http://localhost:9000', {
// @ts-ignore // @ts-expect-error
extraHeaders: { Authorization: `Bearer ${token}` } extraHeaders: { Authorization: `Bearer ${token}` }
}) })
socket.on('connect', () => { socket.on('connect', () => {
@ -108,7 +108,7 @@ describe('authorizer', () => {
}) })
describe('unsigned token', () => { describe('unsigned token', () => {
let token = const token =
'eyJhbGciOiJub25lIiwiY3R5IjoiSldUIn0.eyJuYW1lIjoiSm9obiBGb28ifQ.' 'eyJhbGciOiJub25lIiwiY3R5IjoiSldUIn0.eyJuYW1lIjoiSm9obiBGb28ifQ.'
beforeEach((done) => { beforeEach((done) => {

View File

@ -1,4 +1,5 @@
import jwt from 'jsonwebtoken' import jwt from 'jsonwebtoken'
import { Socket } from 'socket.io'
class UnauthorizedError extends Error { class UnauthorizedError extends Error {
public inner: { message: string } public inner: { message: string }
@ -17,134 +18,70 @@ class UnauthorizedError extends Error {
} }
} }
function noQsMethod (options: any) { /**
const defaults = { required: true } * If JwtAuthOptions.secret is a function, then this is the signature of the callback function provided to that function
options = Object.assign(defaults, options) */
export type JwtSecretFuncCallback = (err: Error | null, secret: string) => void
return (socket: any) => { /**
const server = socket.server * This is a function with two args payload, and done.
*
* `request` is the original request
* `payload` is the decoded JWT payload
* `callback` is an error-first callback defined below
*/
export type JwtSecretFunc = (
request: any,
payload: any,
callback: JwtSecretFuncCallback
) => void
let auth_timeout: any = null /**
if (options.required) { * This is an object literal that contains options.
auth_timeout = setTimeout(() => { */
socket.disconnect('unauthorized') export interface JwtAuthOptions {
}, options.timeout || 5000) auth_header_required?: boolean
secret: string | JwtSecretFunc
timeout?: number // In milliseconds to handle the second round trip.
callback?: boolean | number // To disconnect socket server-side without a client-side callback if no valid token.
decodedPropertyName?: string // Property to store the decoded token to.
handshake?: boolean // Used to trigger a single round trip authentication.
required?: boolean
} }
socket.on('authenticate', (data: any) => { /**
if (options.required) { * Defines possible errors for the secret-callback.
clearTimeout(auth_timeout) */
interface ISocketIOError {
readonly code: string
readonly message: string
} }
const onError = (err: any, code: any) => { interface AuthOptions extends JwtAuthOptions {
if (err) { additional_auth?: (
code = code || 'unknown' decoded: object,
const error = new UnauthorizedError(code, { onSuccess: () => void,
message: onError: (err: string | ISocketIOError, code: string) => void
Object.prototype.toString.call(err) === '[object Object]' && ) => void
err.message customDecoded?: (decoded: object) => object
? err.message encodedPropertyName: string
: err decodedPropertyName: string
}) cookie?: string
let callback_timeout: any
// If callback explicitly set to false, start timeout to disconnect socket
if (
options.callback === false ||
typeof options.callback === 'number'
) {
if (typeof options.callback === 'number') {
if (options.callback < 0) {
// If callback is negative(invalid value), make it positive
options.callback = Math.abs(options.callback)
}
} }
callback_timeout = setTimeout( type ISocketIOMiddleware = (socket: Socket, fn: (err?: any) => void) => void
() => {
socket.disconnect('unauthorized')
},
options.callback === false ? 0 : options.callback
)
}
socket.emit('unauthorized', error, () => { /**
if (typeof options.callback === 'number') { * @description This function returns a middleware function for use with Socket.IO that authenticates a new connection.
clearTimeout(callback_timeout) * @param options is an object literal that contains options.
} */
socket.disconnect('unauthorized') export function authorize (authOptions: JwtAuthOptions): ISocketIOMiddleware {
}) const options: AuthOptions = Object.assign(
return null
}
}
const token = options.cookie
? socket.request.cookies[options.cookie]
: data
? data.token
: undefined
if (!token || typeof token !== 'string') {
return onError({ message: 'invalid token datatype' }, 'invalid_token')
}
// Store encoded JWT
socket[options.encodedPropertyName] = token
const onJwtVerificationReady = (err: any, decoded: any) => {
if (err) {
return onError(err, 'invalid_token')
}
// success handler
const onSuccess = () => {
socket[options.decodedPropertyName] = options.customDecoded
? options.customDecoded(decoded)
: decoded
socket.emit('authenticated')
if (server.$emit) {
server.$emit('authenticated', socket)
} else {
// try getting the current namespace otherwise fallback to all sockets.
const namespace =
(server.nsps && socket.nsp && server.nsps[socket.nsp.name]) ||
server.sockets
// explicit namespace
namespace.emit('authenticated', socket)
}
}
if (
options.additional_auth &&
typeof options.additional_auth === 'function'
) {
options.additional_auth(decoded, onSuccess, onError)
} else {
onSuccess()
}
}
const onSecretReady = (err: any, secret: any) => {
if (err || !secret) {
return onError(err, 'invalid_secret')
}
jwt.verify(token, secret, options, onJwtVerificationReady)
}
getSecret(socket.request, options.secret, token, onSecretReady)
})
}
}
export function authorize (options: any) {
options = Object.assign(
{ {
decodedPropertyName: 'decoded_token', decodedPropertyName: 'decoded_token',
encodedPropertyName: 'encoded_token' encodedPropertyName: 'encoded_token'
}, },
options authOptions
) )
if ( if (
@ -161,14 +98,14 @@ export function authorize (options: any) {
} }
const defaults = { const defaults = {
success: (socket: any, accept: Function) => { success: (socket: Socket, accept: Function) => {
if (socket.request) { if (socket.request) {
accept() accept()
} else { } else {
accept(null, true) accept(null, true)
} }
}, },
fail: (error: Error, socket: any, accept: Function) => { fail: (error: Error, socket: Socket, accept: Function) => {
if (socket.request) { if (socket.request) {
accept(error) accept(error)
} else { } else {
@ -179,8 +116,7 @@ export function authorize (options: any) {
const auth = Object.assign(defaults, options) const auth = Object.assign(defaults, options)
return (socket: any, accept: Function) => { return (socket: Socket, accept: Function) => {
'use strict' // Node 4.x workaround
let token: any, error: any let token: any, error: any
const handshake = socket.handshake const handshake = socket.handshake
@ -205,7 +141,7 @@ export function authorize (options: any) {
} }
// Check if the header has to include authentication // Check if the header has to include authentication
if (options.auth_header_required && !token) { if (options.auth_header_required && token == null) {
return auth.fail( return auth.fail(
new UnauthorizedError('missing_authorization_header', { new UnauthorizedError('missing_authorization_header', {
message: 'Server requires Authorization Header' message: 'Server requires Authorization Header'
@ -224,7 +160,7 @@ export function authorize (options: any) {
token = req.query.token token = req.query.token
} }
if (!token) { if (token == null) {
error = new UnauthorizedError('credentials_required', { error = new UnauthorizedError('credentials_required', {
message: 'no token provided' message: 'no token provided'
}) })
@ -232,17 +168,17 @@ export function authorize (options: any) {
} }
// Store encoded JWT // Store encoded JWT
socket[options.encodedPropertyName] = token socket = Object.assign(socket, { [options.encodedPropertyName]: token })
const onJwtVerificationReady = (err: any, decoded: any) => { const onJwtVerificationReady = (err: any) => {
if (err) { if (err != null) {
error = new UnauthorizedError(err.code || 'invalid_token', err) error = new UnauthorizedError(err.code || 'invalid_token', err)
return auth.fail(error, socket, accept) return auth.fail(error, socket, accept)
} }
socket[options.decodedPropertyName] = options.customDecoded socket = Object.assign(socket, {
? options.customDecoded(decoded) [options.decodedPropertyName]: options.customDecoded
: decoded })
return auth.success(socket, accept) return auth.success(socket, accept)
} }
@ -253,14 +189,14 @@ export function authorize (options: any) {
return auth.fail(error, socket, accept) return auth.fail(error, socket, accept)
} }
jwt.verify(token, secret, options, onJwtVerificationReady) jwt.verify(token, secret, onJwtVerificationReady)
} }
getSecret(req, options.secret, token, onSecretReady) getSecret(req, options.secret, token, onSecretReady)
} }
} }
function getSecret (request: any, secret: any, token: any, callback: Function) { function getSecret (request: any, secret: any, token: string, callback: Function) {
if (typeof secret === 'function') { if (typeof secret === 'function') {
if (!token) { if (!token) {
return callback({ return callback({
@ -282,9 +218,9 @@ function getSecret (request: any, secret: any, token: any, callback: Function) {
}) })
} }
const decodedToken: any = jwt.decode(token, { complete: true }) const decodedToken = jwt.decode(token, { complete: true }) as { [key: string]: any }
if (!decodedToken) { if (decodedToken == null) {
return callback({ code: 'invalid_token', message: 'jwt malformed' }) return callback({ code: 'invalid_token', message: 'jwt malformed' })
} }
@ -299,3 +235,111 @@ function getSecret (request: any, secret: any, token: any, callback: Function) {
callback(null, secret) callback(null, secret)
} }
} }
function noQsMethod (options: AuthOptions): ISocketIOMiddleware {
const defaults = { required: true }
options = Object.assign(defaults, options)
return (socket: Socket) => {
let auth_timeout: NodeJS.Timeout | null = null
if (options.required) {
auth_timeout = setTimeout(() => {
socket.disconnect(true)
}, options.timeout ?? 5000)
}
socket.on('authenticate', (data: any) => {
if (options.required && auth_timeout != null) {
clearTimeout(auth_timeout)
}
const onError = (err: any, code: string) => {
if (err) {
code = code ?? 'unknown'
const error = new UnauthorizedError(code, {
message:
Object.prototype.toString.call(err) === '[object Object]' &&
err.message
? err.message
: err
})
let callback_timeout: NodeJS.Timeout | null = null
// If callback explicitly set to false, start timeout to disconnect socket
if (
options.callback === false ||
typeof options.callback === 'number'
) {
if (typeof options.callback === 'number') {
if (options.callback < 0) {
// If callback is negative(invalid value), make it positive
options.callback = Math.abs(options.callback)
}
}
callback_timeout = setTimeout(
() => {
socket.disconnect(true)
},
options.callback === false ? 0 : options.callback
)
}
socket.emit('unauthorized', error, () => {
if (typeof options.callback === 'number' && callback_timeout != null) {
clearTimeout(callback_timeout)
}
socket.disconnect(true)
})
return null
}
}
const token = options.cookie
? socket.request.cookies[options.cookie]
: data
? data.token
: undefined
if (token == null || typeof token !== 'string') {
return onError({ message: 'invalid token datatype' }, 'invalid_token')
}
// Store encoded JWT
socket = Object.assign(socket, { [options.encodedPropertyName]: token })
const onJwtVerificationReady = (err: any, decoded: any) => {
if (err) {
return onError(err, 'invalid_token')
}
// success handler
const onSuccess = () => {
socket = Object.assign(socket, {
[options.decodedPropertyName]: options.customDecoded
})
socket.emit('authenticated')
}
if (
options.additional_auth != null &&
typeof options.additional_auth === 'function'
) {
options.additional_auth(decoded, onSuccess, onError)
} else {
onSuccess()
}
}
const onSecretReady = (err: any, secret: string) => {
if (err != null || secret == null) {
return onError(err, 'invalid_secret')
}
jwt.verify(token, secret, onJwtVerificationReady)
}
getSecret(socket.request, options.secret, token, onSecretReady)
})
}
}