Skip to content

Commit

Permalink
Add socket authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinsandow committed Jul 25, 2022
1 parent 8419708 commit e2c27f6
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 5 deletions.
1 change: 1 addition & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ module.exports = {
},
},
rules: {
'no-param-reassign': [2, { props: false }],
'import/extensions': ['error', { ts: 'never', ignorePackages: true }],
'no-shadow': 'off',
'@typescript-eslint/no-shadow': ['error'],
Expand Down
4 changes: 4 additions & 0 deletions client/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// eslint-disable-next-line import/prefer-default-export
export function generateToken(username: string, password: string): string {
return Buffer.from(`${username}:${password}`).toString('base64')
}
3 changes: 3 additions & 0 deletions client/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const uri = process.env?.SERVER_URI || 'http://localhost:3000'
export const username = process.env?.RPG_FOR_BOTS_USERNAME || 'foobar'
export const password = process.env?.RPG_FOR_BOTS_PASSWORD || 'foobar'
9 changes: 7 additions & 2 deletions client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ import { io, Socket } from 'socket.io-client'

import { ClientToServerEvents, ServerToClientEvents } from '../shared/socket'

const uri = process.env?.SERVER_URI || 'http://localhost:3000'
import { uri, username, password } from './env'
import { generateToken } from './auth'

const socket: Socket<ServerToClientEvents, ClientToServerEvents> = io(uri)
const socket: Socket<ServerToClientEvents, ClientToServerEvents> = io(uri, {
auth: {
token: generateToken(username, password),
},
})

const start = Date.now()

Expand Down
23 changes: 23 additions & 0 deletions server/aurh.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
type Credentials = {
username: string
password: string
}

export function parseToken(token: string): Credentials {
const [username, password] = Buffer.from(token, 'base64')
.toString()
.split(':')

return {
username: username ?? '',
password: password ?? '',
}
}

export function validateCredentials({
username,
password,
}: Credentials): boolean {
// TODO: do real validation in the future
return username === password
}
2 changes: 2 additions & 0 deletions server/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// eslint-disable-next-line import/prefer-default-export
export const port = +(process.env?.PORT || '') || 3000
29 changes: 27 additions & 2 deletions server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,51 @@ import {
SocketData,
} from '../shared/socket'

const port = +(process.env?.PORT || '') || 3000
import { port } from './env'
import { parseToken, validateCredentials } from './aurh'

const server = new Server<
ClientToServerEvents,
ServerToClientEvents,
InterServerEvents,
SocketData
>()
server.listen(port)

server.use((socket, next) => {
const credentials = parseToken(socket.handshake.auth?.token || '')

if (!validateCredentials(credentials)) {
console.debug(
`[${socket.id}] Invalid credentials for user "${credentials.username}" from ${socket.handshake.address}`,
)
next(new Error('Invalid credentials'))
return
}

socket.data.username = credentials.username
next()
})

server.on('connection', (socket) => {
console.debug(
`[${socket.id}] New connection from ${socket.handshake.address}`,
)

if (socket.data.username) {
console.log(`[${socket.id}] User "${socket.data.username}" came online`)
}

socket.on('disconnect', () => {
if (socket.data.username) {
console.log(`[${socket.id}] User "${socket.data.username}" went offline`)
}

console.debug(`[${socket.id}] Connection closed`)
})

socket.on('ping', (callback) => {
callback()
})
})

server.listen(port)
4 changes: 3 additions & 1 deletion shared/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ export interface ClientToServerEvents {
export interface InterServerEvents {}

// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface SocketData {}
export interface SocketData {
username: string
}

0 comments on commit e2c27f6

Please sign in to comment.