46 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
ad86800d8c chore(release): v2.0.0 2021-02-22 13:07:40 +01:00
a14d4e937b feat: usage of auth option to send credentials
BREAKING CHANGE: extraHeaders with Authorization doesn't work anymore

See: https://socket.io/docs/v3/middlewares/#Sending-credentials
2021-02-22 13:00:53 +01:00
4ba3e3bccb build(deps-dev): bump @types/node from 14.14.30 to 14.14.31 (#38) 2021-02-22 11:09:41 +01:00
907b82fca9 build(deps-dev): bump release-it from 14.4.0 to 14.4.1 (#40) 2021-02-22 11:09:26 +01:00
4c469169f4 build(deps-dev): bump husky from 5.0.9 to 5.1.0 (#39) 2021-02-22 11:09:01 +01:00
d5f402df86 build(deps-dev): bump @types/node from 14.14.28 to 14.14.30 (#36) 2021-02-19 09:24:50 +01:00
d01bcc29fa docs: add authorize options 2021-02-18 20:14:56 +01:00
55a5f71b6e build(deps-dev): bump @types/node from 14.14.27 to 14.14.28 (#35) 2021-02-15 14:00:04 +01:00
7ccdb8f9a0 chore: general improvements of config files 2021-02-14 19:28:15 +01:00
b61ddd1872 build(deps-dev): bump @types/node from 14.14.25 to 14.14.26 (#33) 2021-02-12 09:14:26 +01:00
ac3b5177e5 build(deps-dev): bump typescript from 4.1.4 to 4.1.5 (#32) 2021-02-11 09:58:40 +01:00
0e8630d145 build(deps-dev): bump ts-jest from 26.5.0 to 26.5.1 (#30) 2021-02-10 12:20:15 +01:00
bb1daa2e28 build(deps-dev): bump typescript from 4.1.3 to 4.1.4 (#31) 2021-02-10 12:19:50 +01:00
17d7f264a4 build(deps-dev): bump husky from 4.3.8 to 5.0.9 (#29) 2021-02-09 20:22:40 +01:00
7f1c25ed98 build(deps): bump actions/cache from v2 to v2.1.4 (#28) 2021-02-08 14:57:20 +01:00
d9fa92cb1c build(deps-dev): bump @types/node from 14.14.22 to 14.14.25 (#27) 2021-02-04 14:36:58 +01:00
b08354f2b2 build(deps-dev): bump socket.io from 3.1.0 to 3.1.1 (#26) 2021-02-04 13:37:42 +01:00
06141ec89d build(deps-dev): bump @types/node from 14.14.22 to 14.14.24 (#25) 2021-02-04 13:37:00 +01:00
113df6f8f7 build(deps-dev): bump release-it from 14.2.2 to 14.3.0 (#24) 2021-02-04 13:36:26 +01:00
a761725e6b build(deps-dev): bump socket.io-client from 3.1.0 to 3.1.1 (#23) 2021-02-04 13:36:00 +01:00
f5a13c01b0 build(deps-dev): bump ts-jest from 26.4.4 to 26.5.0 (#22) 2021-02-01 18:16:22 +01:00
26 changed files with 25101 additions and 120 deletions

1
.commitlintrc.json Normal file
View File

@ -0,0 +1 @@
{ "extends": ["@commitlint/config-conventional"] }

View File

@ -1,6 +1,7 @@
--- ---
name: '🐛 Bug Report' name: '🐛 Bug Report'
about: 'Report an unexpected problem or unintended behavior.' about: 'Report an unexpected problem or unintended behavior.'
title: '[Bug]'
labels: 'bug' labels: 'bug'
--- ---

View File

@ -1,20 +1,18 @@
--- ---
name: '📜 Documentation' name: '📜 Documentation'
about: 'Correct spelling errors, improvements or additions to documentation files (README, CONTRIBUTING...).' about: 'Correct spelling errors, improvements or additions to documentation files (README, CONTRIBUTING...).'
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 : <!-- Please uncomment the type of documentation problem this issue address -->
- [ ] Is Missing <!-- Documentation is Missing -->
- [ ] Is Confusing <!-- Documentation is Confusing -->
- [ ] Has Typo errors <!-- Documentation has Typo errors -->
- [ ] Not Sure?
### Proposal ## Proposal

View File

@ -1,19 +1,20 @@
--- ---
name: '✨ Feature Request' name: '✨ Feature Request'
about: 'Suggest a new feature idea.' about: 'Suggest a new feature idea.'
title: '[Feature]'
labels: 'feature request' labels: 'feature request'
--- ---
<!-- Please make sure your issue has not already been fixed. --> <!-- Please make sure your issue has not already been fixed. -->
### Description ## Description
<!-- A clear and concise description of the problem or missing capability... --> <!-- A clear and concise description of the problem or missing capability... -->
### Describe the solution you'd like ## Describe the solution you'd like
<!-- If you have a solution in mind, please describe it. --> <!-- If you have a solution in mind, please describe it. -->
### Describe alternatives you've considered ## Describe alternatives you've considered
<!-- Have you considered any alternative solutions or workarounds? --> <!-- Have you considered any alternative solutions or workarounds? -->

View File

@ -1,21 +1,20 @@
--- ---
name: '🔧 Improvement' name: '🔧 Improvement'
about: 'Improve structure/format/performance/refactor/tests of the code.' about: 'Improve structure/format/performance/refactor/tests of the code.'
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 : <!-- Please uncomment the type of improvements this issue address -->
- [ ] Files and Folders Structure <!-- Files and Folders Structure -->
- [ ] Performance <!-- Performance -->
- [ ] Refactoring code <!-- Refactoring code -->
- [ ] Tests <!-- Tests -->
- [ ] Not Sure? <!-- Not Sure? -->
### Proposal ## Proposal

View File

@ -1,6 +1,7 @@
--- ---
name: '🙋 Question' name: '🙋 Question'
about: 'Further information is requested.' about: 'Further information is requested.'
title: '[Question]'
labels: 'question' labels: 'question'
--- ---

View File

@ -3,25 +3,12 @@
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.
--> -->
### What type of change does this PR introduce? ## What changes this PR introduce?
- [ ] Bugfix ## List any relevant issue numbers
- [ ] Feature
- [ ] Refactor
- [ ] Documentation
- [ ] Not Sure?
### Does this PR introduce breaking changes? ## Is there anything you'd like reviewers to focus on?
- [ ] Yes
- [ ] No
### List any relevant issue numbers:
### Description:

View File

@ -12,9 +12,11 @@ on:
jobs: jobs:
commitlint: commitlint:
if: ${{ (github.event_name == 'push') || (github.event_name == 'pull_request_review' && github.event.review.state == 'approved' && (github.event.review.author_association == 'COLLABORATOR' || github.event.review.author_association == 'MEMBER' || github.event.review.author_association == 'OWNER') && !github.event.pull_request.draft && github.event.pull_request.state == 'open') }} if: ${{ (github.event_name == 'push') || (github.event_name == 'pull_request_review' && github.event.review.state == 'approved' && (github.event.review.author_association == 'COLLABORATOR' || github.event.review.author_association == 'MEMBER' || github.event.review.author_association == 'OWNER') && !github.event.pull_request.draft && github.event.pull_request.state == 'open') }}
runs-on: ubuntu-latest runs-on: 'ubuntu-latest'
steps: steps:
- 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

@ -12,7 +12,7 @@ on:
jobs: jobs:
ci_app: ci_app:
if: ${{ (github.event_name == 'push') || (github.event_name == 'pull_request_review' && github.event.review.state == 'approved' && (github.event.review.author_association == 'COLLABORATOR' || github.event.review.author_association == 'MEMBER' || github.event.review.author_association == 'OWNER') && !github.event.pull_request.draft && github.event.pull_request.state == 'open') }} if: ${{ (github.event_name == 'push') || (github.event_name == 'pull_request_review' && github.event.review.state == 'approved' && (github.event.review.author_association == 'COLLABORATOR' || github.event.review.author_association == 'MEMBER' || github.event.review.author_association == 'OWNER') && !github.event.pull_request.draft && github.event.pull_request.state == 'open') }}
runs-on: ubuntu-latest runs-on: 'ubuntu-latest'
strategy: strategy:
matrix: matrix:
node-version: [14.x] node-version: [14.x]
@ -20,23 +20,25 @@ 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' uses: 'actions/cache@v2.1.4'
with: with:
path: | path: '.npm'
**/node_modules key: ${{ runner.os }}-${{ hashFiles('**/package-lock.json') }}
key: ${{ runner.os }}-${{ hashFiles('**/package.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'
- name: 'MarkdownLint'
run: 'npm run markdownlint'
- name: 'Build' - name: 'Build'
run: 'npm run build' run: 'npm run build'

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' 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

1
.husky/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
_

4
.husky/commit-msg Executable file
View File

@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install commitlint --edit

5
.husky/pre-commit Executable file
View File

@ -0,0 +1,5 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run lint
npm run markdownlint

7
.markdownlint.json Normal file
View File

@ -0,0 +1,7 @@
{
"default": true,
"MD013": false,
"MD024": false,
"MD033": false,
"MD041": false
}

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,47 @@
# 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)
### Features
- usage of auth option to send credentials ([a14d4e9](https://github.com/Thream/socketio-jwt/commit/a14d4e937b764fdf4fb6b173c55b6f49688766dd))
See: <https://socket.io/docs/v3/middlewares/#Sending-credentials>
### BREAKING CHANGES
- `extraHeaders` with `Authorization` doesn't work anymore
### Migration
You need to change the way to connect client side.
Before :
```ts
import { io } from 'socket.io-client'
const socket = io('http://localhost:9000', {
extraHeaders: { Authorization: `Bearer ${yourJWT}` }
})
```
After :
```ts
import { io } from 'socket.io-client'
const socket = io('http://localhost:9000', {
auth: { token: `Bearer ${yourJWT}` }
})
```
## [1.1.1](https://github.com/Thream/socketio-jwt/compare/v1.1.0...v1.1.1) (2021-01-28) ## [1.1.1](https://github.com/Thream/socketio-jwt/compare/v1.1.0...v1.1.1) (2021-01-28)
### Bug Fixes ### Bug Fixes

View File

@ -87,14 +87,46 @@ 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
- `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`)
- `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
```ts ```ts
import { io } from 'socket.io-client' import { io } from 'socket.io-client'
// Require Bearer Tokens to be passed in as an Authorization Header // Require Bearer Token
const socket = io('http://localhost:9000', { const socket = io('http://localhost:9000', {
extraHeaders: { Authorization: `Bearer ${yourJWT}` } auth: { token: `Bearer ${yourJWT}` }
}) })
// Handling token expiration // Handling token expiration
@ -114,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

View File

@ -1 +0,0 @@
module.exports = { extends: ['@commitlint/config-conventional'] }

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": "1.1.1", "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",
@ -25,15 +25,11 @@
"url": "https://github.com/Thream/socketio-jwt/issues" "url": "https://github.com/Thream/socketio-jwt/issues"
}, },
"homepage": "https://github.com/Thream/socketio-jwt#readme", "homepage": "https://github.com/Thream/socketio-jwt#readme",
"husky": {
"hooks": {
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
"pre-commit": "npm run lint"
}
},
"release-it": { "release-it": {
"git": { "git": {
"commitMessage": "chore(release): v${version}" "commit": false,
"push": false,
"tag": false
}, },
"github": { "github": {
"release": false "release": false
@ -44,6 +40,8 @@
"hooks": { "hooks": {
"before:init": [ "before:init": [
"npm run lint", "npm run lint",
"npm run markdownlint",
"npm run build",
"npm run test" "npm run test"
] ]
}, },
@ -62,22 +60,26 @@
"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",
"lint": "ts-standard | snazzy", "markdownlint": "markdownlint '**/*.md' --dot --ignore node_modules",
"format": "ts-standard --fix | snazzy", "lint": "ts-standard",
"release": "release-it", "release": "release-it",
"test": "jest", "test": "jest",
"test:watchAll": "jest --watchAll", "postinstall": "husky install",
"test:clearCache": "jest --clearCache" "prepublishOnly": "pinst --disable",
"postpublish": "pinst --enable"
}, },
"peerDependencies": { "peerDependencies": {
"socket.io": ">=3.0.0" "socket.io": ">=3.0.0"
@ -86,26 +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.22", "@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": "4.3.8", "husky": "5.1.3",
"jest": "26.6.3", "jest": "26.6.3",
"release-it": "14.2.2", "markdownlint-cli": "0.27.1",
"pinst": "2.1.6",
"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.0", "socket.io-client": "3.1.2",
"socket.io-client": "3.1.0", "ts-jest": "26.5.3",
"ts-jest": "26.4.4",
"ts-standard": "10.0.0", "ts-standard": "10.0.0",
"typescript": "4.1.3" "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 = ''
@ -31,7 +31,7 @@ describe('authorize - with secret as string in options', () => {
it('should emit error with bad token format', (done) => { it('should emit error with bad token format', (done) => {
const socket = io('http://localhost:9000', { const socket = io('http://localhost:9000', {
extraHeaders: { Authorization: 'testing' } auth: { token: 'testing' }
}) })
socket.on('connect_error', (err: any) => { socket.on('connect_error', (err: any) => {
expect(err.data.message).toEqual( expect(err.data.message).toEqual(
@ -45,7 +45,7 @@ describe('authorize - with secret as string in options', () => {
it('should emit error with unauthorized handshake', (done) => { it('should emit error with unauthorized handshake', (done) => {
const socket = io('http://localhost:9000', { const socket = io('http://localhost:9000', {
extraHeaders: { Authorization: 'Bearer testing' } auth: { token: 'Bearer testing' }
}) })
socket.on('connect_error', (err: any) => { socket.on('connect_error', (err: any) => {
expect(err.data.message).toEqual( expect(err.data.message).toEqual(
@ -59,7 +59,7 @@ describe('authorize - with secret as string in options', () => {
it('should connect the user', (done) => { it('should connect the user', (done) => {
const socket = io('http://localhost:9000', { const socket = io('http://localhost:9000', {
extraHeaders: { Authorization: `Bearer ${token}` } auth: { token: `Bearer ${token}` }
}) })
socket.on('connect', () => { socket.on('connect', () => {
socket.close() socket.close()
@ -93,7 +93,7 @@ describe('authorize - with secret as callback in options', () => {
it('should connect the user', (done) => { it('should connect the user', (done) => {
const socket = io('http://localhost:9000', { const socket = io('http://localhost:9000', {
extraHeaders: { Authorization: `Bearer ${token}` } auth: { token: `Bearer ${token}` }
}) })
socket.on('connect', () => { socket.on('connect', () => {
socket.close() socket.close()
@ -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,15 +35,16 @@ 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 authorizationHeader = socket.request.headers.authorization const { token } = socket.handshake.auth
if (authorizationHeader != null) { if (token != null) {
const tokenSplitted = authorizationHeader.split(' ') const tokenSplitted = token.split(' ')
if (tokenSplitted.length !== 2 || tokenSplitted[0] !== 'Bearer') { if (tokenSplitted.length !== 2 || tokenSplitted[0] !== 'Bearer') {
return next( return next(
new UnauthorizedError('credentials_bad_format', { new UnauthorizedError('credentials_bad_format', {
@ -59,7 +61,6 @@ export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => {
}) })
) )
} }
// Store encoded JWT
socket.encodedToken = encodedToken socket.encodedToken = encodedToken
let keySecret: string | null = null let keySecret: string | null = null
let decodedToken: any let decodedToken: any
@ -78,8 +79,14 @@ export const authorize = (options: AuthorizeOptions): SocketIOMiddleware => {
}) })
) )
} }
// Store decoded JWT
socket.decodedToken = decodedToken socket.decodedToken = decodedToken
if (onAuthentication != null) {
try {
socket.user = await onAuthentication(decodedToken)
} catch (err) {
return next(err)
}
}
return next() return next()
} }
} }