25 Commits

Author SHA1 Message Date
88bfd46c33 chore(release): v2.1.0 2021-03-08 14:37:14 +01:00
4b95cd4293 chore: improve config files 2021-03-08 14:33:53 +01:00
c7f64a6312 feat: add optional onAuthentication option to add user property in socket object (#62) 2021-03-08 14:10:42 +01:00
89518a45d5 build(deps-dev): bump @types/node from 14.14.31 to 14.14.32 (#63) 2021-03-08 13:45:56 +01:00
a5da945bb5 build(deps-dev): bump typescript from 4.2.2 to 4.2.3 (#61) 2021-03-05 14:48:27 +01:00
ce798241e5 build(deps-dev): bump ts-jest from 26.5.2 to 26.5.3 (#59) 2021-03-04 12:32:10 +01:00
8dfddbd5b4 build(deps): bump wagoid/commitlint-github-action from v3.0.1 to v3.0.6 (#58) 2021-03-03 13:21:11 +01:00
e353d2a1fe build(deps-dev): bump markdownlint-cli from 0.27.0 to 0.27.1 (#57) 2021-03-03 13:20:58 +01:00
5a02e25f86 build(deps-dev): bump markdownlint-cli from 0.26.0 to 0.27.0 (#55) 2021-03-02 11:44:26 +01:00
f9678604cc build(deps-dev): bump husky from 5.1.2 to 5.1.3 (#56) 2021-03-02 11:41:42 +01:00
c5121fb008 build(deps-dev): bump @commitlint/config-conventional (#54) 2021-03-01 11:40:39 +01:00
95e461540a build(deps-dev): bump @commitlint/cli from 12.0.0 to 12.0.1 (#52) 2021-03-01 11:37:06 +01:00
7687ddfe83 build(deps-dev): bump husky from 5.1.1 to 5.1.2 (#53) 2021-03-01 11:36:53 +01:00
565f83db9d ci(commitlint): add configFile 2021-02-26 11:02:14 +01:00
6953d6952b build(deps-dev): bump socket.io from 3.1.1 to 3.1.2 (#51) 2021-02-26 10:56:11 +01:00
3d109f362f build(deps-dev): bump socket.io-client from 3.1.1 to 3.1.2 (#50) 2021-02-26 10:55:31 +01:00
ced2f5db1e build(deps): bump wagoid/commitlint-github-action from v2 to v3 (#49) 2021-02-25 07:55:53 +01:00
0971dcc1bb build(deps-dev): bump ts-jest from 26.5.1 to 26.5.2 (#47) 2021-02-24 12:57:00 +01:00
a710630ccf build(deps-dev): bump typescript from 4.1.5 to 4.2.2 (#48) 2021-02-24 12:56:37 +01:00
e50e7ea00e build(deps-dev): bump @release-it/conventional-changelog (#45) 2021-02-23 11:11:26 +01:00
cff7892c3d build(deps-dev): bump husky from 5.1.0 to 5.1.1 (#44) 2021-02-23 11:11:08 +01:00
17232c18e1 build(deps-dev): bump pinst from 2.1.4 to 2.1.6 (#46) 2021-02-23 11:10:52 +01:00
8f896eb93b build(deps-dev): bump @commitlint/cli from 11.0.0 to 12.0.0 (#43) 2021-02-23 11:09:59 +01:00
814fc781e3 build(deps-dev): bump @commitlint/config-conventional (#42) 2021-02-23 11:09:19 +01:00
4291da1417 build(deps): update actions/setup-node requirement to v2.1.5 (#41) 2021-02-23 11:09:02 +01:00
18 changed files with 24994 additions and 72 deletions

View File

@ -5,11 +5,7 @@ title: '[Documentation]'
labels: 'documentation' labels: 'documentation'
--- ---
<!-- <!-- Please make sure your issue has not already been fixed. -->
Please make sure your issue has not already been fixed.
Please place an x (no spaces - [x]) in all [ ] that apply.
-->
## Documentation ## Documentation

View File

@ -5,11 +5,7 @@ title: '[Improvement]'
labels: 'improvement' labels: 'improvement'
--- ---
<!-- <!-- Please make sure your issue has not already been fixed. -->
Please make sure your issue has not already been fixed.
Please place an x (no spaces - [x]) in all [ ] that apply.
-->
## Type of Improvement ## Type of Improvement

View File

@ -3,9 +3,7 @@
Please first discuss the change you wish to make via issue before making a change. It might avoid a waste of your time. Please first discuss the change you wish to make via issue before making a change. It might avoid a waste of your time.
Before submitting your contribution, please take a moment to review this document: Before submitting your contribution, please take a moment to review this document:
https://github.com/Thream/socketio-jwt/blob/master/.github/CONTRIBUTING.md https://github.com/Thream/socketio-jwt/blob/master/CONTRIBUTING.md
Please place an x (no spaces - [x]) in all [ ] that apply.
--> -->

View File

@ -17,4 +17,6 @@ jobs:
- uses: 'actions/checkout@v2' - uses: 'actions/checkout@v2'
with: with:
fetch-depth: 0 fetch-depth: 0
- uses: 'wagoid/commitlint-github-action@v2' - uses: 'wagoid/commitlint-github-action@v3.0.6'
with:
configFile: '.commitlintrc.json'

View File

@ -20,18 +20,18 @@ jobs:
- uses: 'actions/checkout@v2' - uses: 'actions/checkout@v2'
- name: Use Node.js ${{ matrix.node-version }} - name: Use Node.js ${{ matrix.node-version }}
uses: 'actions/setup-node@v2.1.4' uses: 'actions/setup-node@v2.1.5'
with: with:
node-version: ${{ matrix.node-version }} node-version: ${{ matrix.node-version }}
- name: 'Cache dependencies' - name: 'Cache dependencies'
uses: 'actions/cache@v2.1.4' uses: 'actions/cache@v2.1.4'
with: with:
path: '**/node_modules' path: '.npm'
key: ${{ runner.os }}-${{ hashFiles('**/package.json') }} key: ${{ runner.os }}-${{ hashFiles('**/package-lock.json') }}
- name: 'Install dependencies' - name: 'Install dependencies'
run: 'npm install' run: 'npm ci --cache .npm --prefer-offline'
- name: 'Lint' - name: 'Lint'
run: 'npm run lint' run: 'npm run lint'

View File

@ -12,19 +12,25 @@ jobs:
steps: steps:
- uses: 'actions/checkout@v2' - uses: 'actions/checkout@v2'
- name: 'Cache dependencies' - name: Use Node.js ${{ matrix.node-version }}
uses: 'actions/cache@v2.1.4' uses: 'actions/setup-node@v2.1.5'
with:
path: '**/node_modules'
key: ${{ runner.os }}-${{ hashFiles('**/package.json') }}
- uses: 'actions/setup-node@v2.1.2'
with: with:
node-version: 14 node-version: 14
registry-url: 'https://registry.npmjs.org/' registry-url: 'https://registry.npmjs.org/'
- run: 'npm install' - name: 'Cache dependencies'
- run: 'npm run build' uses: 'actions/cache@v2.1.4'
- run: 'npm publish --access public' with:
path: '.npm'
key: ${{ runner.os }}-${{ hashFiles('**/package-lock.json') }}
- name: 'Install dependencies'
run: 'npm ci --cache .npm --prefer-offline'
- name: 'Build'
run: 'npm run build'
- name: 'Publish package on npm'
run: 'npm publish --access public'
env: env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}

15
.gitignore vendored
View File

@ -2,9 +2,7 @@
# dependencies # dependencies
node_modules node_modules
.pnp .npm
.pnp.js
.yarn
# production # production
build build
@ -12,19 +10,8 @@ build
# testing # testing
coverage coverage
# envs
.env
.env.production
# debug # debug
npm-debug.log* npm-debug.log*
yarn-debug.log*
yarn-error.log*
# lockfiles
package-lock.json
yarn.lock
pnpm-lock.yaml
# editors # editors
.vscode .vscode

2
.husky/.gitignore vendored
View File

@ -1 +1 @@
_ _

1
.npmrc
View File

@ -1,2 +1 @@
package-lock=false
save-exact=true save-exact=true

View File

@ -1,2 +0,0 @@
--install.no-lockfile true
save-exact true

View File

@ -1,5 +1,11 @@
# Changelog # Changelog
## [2.1.0](https://github.com/Thream/socketio-jwt/compare/v2.0.0...v2.1.0) (2021-03-08)
### Features
- add optional `onAuthentication` option to add `user` property in `socket` object ([#62](https://github.com/Thream/socketio-jwt/issues/62)) ([c7f64a6](https://github.com/Thream/socketio-jwt/commit/c7f64a6312a3e1f6f04918cb7cd415ddef7a11e5))
## [2.0.0](https://github.com/Thream/socketio-jwt/compare/v1.1.1...v2.0.0) (2021-02-22) ## [2.0.0](https://github.com/Thream/socketio-jwt/compare/v1.1.1...v2.0.0) (2021-02-22)
### Features ### Features

View File

@ -87,10 +87,37 @@ io.on('connection', async (socket) => {
}) })
``` ```
### Server side with `onAuthentication` (example)
```ts
import { Server } from 'socket.io'
import { authorize } from '@thream/socketio-jwt'
const io = new Server(9000)
io.use(
authorize({
secret: 'your secret or public key',
onAuthentication: async decodedToken => {
// return the object that you want to add to the user property
// or throw an error if the token is unauthorized
}
})
)
io.on('connection', async (socket) => {
// jwt payload of the connected client
console.log(socket.decodedToken)
// You can do the same things of the previous example there...
// user object returned in onAuthentication
console.log(socket.user)
})
```
### `authorize` options ### `authorize` options
- `secret` is a string containing the secret for HMAC algorithms, or a function that should fetch the secret or public key as shown in the example with `jwks-rsa`. - `secret` is a string containing the secret for HMAC algorithms, or a function that should fetch the secret or public key as shown in the example with `jwks-rsa`.
- `algorithms` (default: `HS256`) - `algorithms` (default: `HS256`)
- `onAuthentication` is a function that will be called with the `decodedToken` as a parameter after the token is authenticated. Return a value to add to the `user` property in the socket object.
### Client side ### Client side
@ -119,7 +146,7 @@ socket.on('messages', (data) => {
Anyone can help to improve the project, submit a Feature Request, a bug report or even correct a simple spelling mistake. Anyone can help to improve the project, submit a Feature Request, a bug report or even correct a simple spelling mistake.
The steps to contribute can be found in the [CONTRIBUTING.md](./.github/CONTRIBUTING.md) file. The steps to contribute can be found in the [CONTRIBUTING.md](./CONTRIBUTING.md) file.
## 📄 License ## 📄 License

24804
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "@thream/socketio-jwt", "name": "@thream/socketio-jwt",
"version": "2.0.0", "version": "2.1.0",
"description": "Authenticate socket.io incoming connections with JWTs.", "description": "Authenticate socket.io incoming connections with JWTs.",
"license": "MIT", "license": "MIT",
"main": "build/index.js", "main": "build/index.js",
@ -60,23 +60,23 @@
"coverageDirectory": "../coverage/" "coverageDirectory": "../coverage/"
}, },
"ts-standard": { "ts-standard": {
"files": [ "ignore": [
"./src/**/*.ts" "build",
"coverage",
"node_modules"
], ],
"envs": [ "envs": [
"node", "node",
"jest" "jest"
] ],
"report": "stylish"
}, },
"scripts": { "scripts": {
"build": "rimraf ./build && tsc", "build": "rimraf ./build && tsc",
"markdownlint": "markdownlint '**/*.md' --ignore node_modules", "markdownlint": "markdownlint '**/*.md' --dot --ignore node_modules",
"lint": "ts-standard | snazzy", "lint": "ts-standard",
"format": "ts-standard --fix | snazzy",
"release": "release-it", "release": "release-it",
"test": "jest", "test": "jest",
"test:watchAll": "jest --watchAll",
"test:clearCache": "jest --clearCache",
"postinstall": "husky install", "postinstall": "husky install",
"prepublishOnly": "pinst --disable", "prepublishOnly": "pinst --disable",
"postpublish": "pinst --enable" "postpublish": "pinst --enable"
@ -88,28 +88,27 @@
"jsonwebtoken": "8.5.1" "jsonwebtoken": "8.5.1"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "11.0.0", "@commitlint/cli": "12.0.1",
"@commitlint/config-conventional": "11.0.0", "@commitlint/config-conventional": "12.0.1",
"@release-it/conventional-changelog": "2.0.0", "@release-it/conventional-changelog": "2.0.1",
"@types/express": "4.17.11", "@types/express": "4.17.11",
"@types/jest": "26.0.20", "@types/jest": "26.0.20",
"@types/jsonwebtoken": "8.5.0", "@types/jsonwebtoken": "8.5.0",
"@types/node": "14.14.31", "@types/node": "14.14.32",
"@types/server-destroy": "1.0.1", "@types/server-destroy": "1.0.1",
"axios": "0.21.1", "axios": "0.21.1",
"express": "4.17.1", "express": "4.17.1",
"husky": "5.1.0", "husky": "5.1.3",
"jest": "26.6.3", "jest": "26.6.3",
"markdownlint-cli": "0.26.0", "markdownlint-cli": "0.27.1",
"pinst": "2.1.4", "pinst": "2.1.6",
"release-it": "14.4.1", "release-it": "14.4.1",
"rimraf": "3.0.2", "rimraf": "3.0.2",
"server-destroy": "1.0.1", "server-destroy": "1.0.1",
"snazzy": "9.0.0", "socket.io": "3.1.2",
"socket.io": "3.1.1", "socket.io-client": "3.1.2",
"socket.io-client": "3.1.1", "ts-jest": "26.5.3",
"ts-jest": "26.5.1",
"ts-standard": "10.0.0", "ts-standard": "10.0.0",
"typescript": "4.1.5" "typescript": "4.2.3"
} }
} }

View File

@ -1,7 +1,7 @@
import axios from 'axios' import axios from 'axios'
import { io } from 'socket.io-client' import { io } from 'socket.io-client'
import { fixtureStart, fixtureStop } from './fixture' import { fixtureStart, fixtureStop, getSocket, Profile } from './fixture'
describe('authorize - with secret as string in options', () => { describe('authorize - with secret as string in options', () => {
let token: string = '' let token: string = ''
@ -101,3 +101,76 @@ describe('authorize - with secret as callback in options', () => {
}) })
}) })
}) })
describe('authorize - with onAuthentication callback in options', () => {
let token: string = ''
let wrongToken: string = ''
beforeEach(async (done) => {
jest.setTimeout(15_000)
await fixtureStart(
async () => {
const response = await axios.post('http://localhost:9000/login')
token = response.data.token
const responseWrong = await axios.post('http://localhost:9000/login-wrong')
wrongToken = responseWrong.data.token
done()
},
{
secret: secretCallback,
onAuthentication: (decodedToken: Profile) => {
if (!decodedToken.checkField) {
throw new Error('Check Field validation failed')
}
return {
email: decodedToken.email
}
}
}
)
})
afterEach((done) => {
fixtureStop(done)
})
it('should connect the user', (done) => {
const socket = io('http://localhost:9000', {
auth: { token: `Bearer ${token}` }
})
socket.on('connect', () => {
socket.close()
done()
})
})
it('should contain user property', (done) => {
const socketServer = getSocket()
socketServer?.on('connection', (client: any) => {
expect(client.user.email).toEqual('john@doe.com')
})
const socket = io('http://localhost:9000', {
auth: { token: `Bearer ${token}` }
})
socket.on('connect', () => {
socket.close()
done()
})
})
it('should emit error when user validation fails', (done) => {
const socket = io('http://localhost:9000', {
auth: { token: `Bearer ${wrongToken}` }
})
socket.on('connect_error', (err: any) => {
try {
expect(err.message).toEqual('Check Field validation failed')
} catch (err) {
socket.close()
done(err)
}
socket.close()
done()
})
})
})

View File

@ -7,6 +7,12 @@ import enableDestroy from 'server-destroy'
import { authorize, AuthorizeOptions } from '../../index' import { authorize, AuthorizeOptions } from '../../index'
export interface Profile {
email: string
id: number
checkField: boolean
}
interface Socket { interface Socket {
io: null | SocketIoServer io: null | SocketIoServer
init: (httpServer: HttpServer | HttpsServer) => void init: (httpServer: HttpServer | HttpsServer) => void
@ -34,9 +40,21 @@ export const fixtureStart = async (
keySecret = await options.secret({ header: { alg: 'RS256' }, payload: '' }) keySecret = await options.secret({ header: { alg: 'RS256' }, payload: '' })
} }
app.post('/login', (_req, res) => { app.post('/login', (_req, res) => {
const profile = { const profile: Profile = {
email: 'john@doe.com', email: 'john@doe.com',
id: 123 id: 123,
checkField: true
}
const token = jwt.sign(profile, keySecret, {
expiresIn: 60 * 60 * 5
})
return res.json({ token })
})
app.post('/login-wrong', (_req, res) => {
const profile: Profile = {
email: 'john@doe.com',
id: 123,
checkField: false
} }
const token = jwt.sign(profile, keySecret, { const token = jwt.sign(profile, keySecret, {
expiresIn: 60 * 60 * 5 expiresIn: 60 * 60 * 5
@ -56,3 +74,7 @@ export const fixtureStop = (callback: Function): void => {
} catch (err) {} } catch (err) {}
callback() callback()
} }
export const getSocket = (): SocketIoServer | null => {
return socket.io
}

View File

@ -14,6 +14,7 @@ interface ExtendedError extends Error {
interface ExtendedSocket { interface ExtendedSocket {
encodedToken?: string encodedToken?: string
decodedToken?: any decodedToken?: any
user?: any
} }
type SocketIOMiddleware = ( type SocketIOMiddleware = (
@ -34,10 +35,11 @@ type SecretCallback = (decodedToken: CompleteDecodedToken) => Promise<string>
export interface AuthorizeOptions { export interface AuthorizeOptions {
secret: string | SecretCallback secret: string | SecretCallback
algorithms?: Algorithm[] algorithms?: Algorithm[]
onAuthentication?: (decodedToken: any) => Promise<any> | any
} }
export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => { export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => {
const { secret, algorithms = ['HS256'] } = options const { secret, algorithms = ['HS256'], onAuthentication } = options
return async (socket, next) => { return async (socket, next) => {
let encodedToken: string | null = null let encodedToken: string | null = null
const { token } = socket.handshake.auth const { token } = socket.handshake.auth
@ -78,6 +80,13 @@ export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => {
) )
} }
socket.decodedToken = decodedToken socket.decodedToken = decodedToken
if (onAuthentication != null) {
try {
socket.user = await onAuthentication(decodedToken)
} catch (err) {
return next(err)
}
}
return next() return next()
} }
} }