Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@thream/socketio-jwt

Package Overview
Dependencies
Maintainers
1
Versions
19
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@thream/socketio-jwt - npm Package Compare versions

Comparing version 2.0.0 to 2.1.0

65

build/__test__/authorize.test.js

@@ -89,1 +89,66 @@ "use strict";

});
describe('authorize - with onAuthentication callback in options', () => {
let token = '';
let wrongToken = '';
beforeEach(async (done) => {
jest.setTimeout(15000);
await fixture_1.fixtureStart(async () => {
const response = await axios_1.default.post('http://localhost:9000/login');
token = response.data.token;
const responseWrong = await axios_1.default.post('http://localhost:9000/login-wrong');
wrongToken = responseWrong.data.token;
done();
}, {
secret: secretCallback,
onAuthentication: (decodedToken) => {
if (!decodedToken.checkField) {
throw new Error('Check Field validation failed');
}
return {
email: decodedToken.email
};
}
});
});
afterEach((done) => {
fixture_1.fixtureStop(done);
});
it('should connect the user', (done) => {
const socket = socket_io_client_1.io('http://localhost:9000', {
auth: { token: `Bearer ${token}` }
});
socket.on('connect', () => {
socket.close();
done();
});
});
it('should contain user property', (done) => {
const socketServer = fixture_1.getSocket();
socketServer === null || socketServer === void 0 ? void 0 : socketServer.on('connection', (client) => {
expect(client.user.email).toEqual('john@doe.com');
});
const socket = socket_io_client_1.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 = socket_io_client_1.io('http://localhost:9000', {
auth: { token: `Bearer ${wrongToken}` }
});
socket.on('connect_error', (err) => {
try {
expect(err.message).toEqual('Check Field validation failed');
}
catch (err) {
socket.close();
done(err);
}
socket.close();
done();
});
});
});

@@ -0,3 +1,10 @@

import { Server as SocketIoServer } from 'socket.io';
import { AuthorizeOptions } from '../../index';
export interface Profile {
email: string;
id: number;
checkField: boolean;
}
export declare const fixtureStart: (done: any, options?: AuthorizeOptions) => Promise<void>;
export declare const fixtureStop: (callback: Function) => void;
export declare const getSocket: () => SocketIoServer | null;

20

build/__test__/fixture/index.js

@@ -6,3 +6,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.fixtureStop = exports.fixtureStart = void 0;
exports.getSocket = exports.fixtureStop = exports.fixtureStart = void 0;
const express_1 = __importDefault(require("express"));

@@ -34,3 +34,4 @@ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));

email: 'john@doe.com',
id: 123
id: 123,
checkField: true
};

@@ -42,2 +43,13 @@ const token = jsonwebtoken_1.default.sign(profile, keySecret, {

});
app.post('/login-wrong', (_req, res) => {
const profile = {
email: 'john@doe.com',
id: 123,
checkField: false
};
const token = jsonwebtoken_1.default.sign(profile, keySecret, {
expiresIn: 60 * 60 * 5
});
return res.json({ token });
});
server = app.listen(9000, done);

@@ -59,1 +71,5 @@ socket.init(server);

exports.fixtureStop = fixtureStop;
const getSocket = () => {
return socket.io;
};
exports.getSocket = getSocket;

@@ -13,2 +13,3 @@ import { Algorithm } from 'jsonwebtoken';

decodedToken?: any;
user?: any;
}

@@ -27,4 +28,5 @@ declare type SocketIOMiddleware = (socket: Socket, next: (err?: ExtendedError) => void) => void;

algorithms?: Algorithm[];
onAuthentication?: (decodedToken: any) => Promise<any> | any;
}
export declare const authorize: (options: AuthorizeOptions) => SocketIOMiddleware;
export {};

@@ -10,3 +10,3 @@ "use strict";

const authorize = (options) => {
const { secret, algorithms = ['HS256'] } = options;
const { secret, algorithms = ['HS256'], onAuthentication } = options;
return async (socket, next) => {

@@ -48,2 +48,10 @@ let encodedToken = null;

socket.decodedToken = decodedToken;
if (onAuthentication != null) {
try {
socket.user = await onAuthentication(decodedToken);
}
catch (err) {
return next(err);
}
}
return next();

@@ -50,0 +58,0 @@ };

# 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)

@@ -4,0 +10,0 @@

41

package.json
{
"name": "@thream/socketio-jwt",
"version": "2.0.0",
"version": "2.1.0",
"description": "Authenticate socket.io incoming connections with JWTs.",

@@ -63,4 +63,6 @@ "license": "MIT",

"ts-standard": {
"files": [
"./src/**/*.ts"
"ignore": [
"build",
"coverage",
"node_modules"
],

@@ -70,13 +72,11 @@ "envs": [

"jest"
]
],
"report": "stylish"
},
"scripts": {
"build": "rimraf ./build && tsc",
"markdownlint": "markdownlint '**/*.md' --ignore node_modules",
"lint": "ts-standard | snazzy",
"format": "ts-standard --fix | snazzy",
"markdownlint": "markdownlint '**/*.md' --dot --ignore node_modules",
"lint": "ts-standard",
"release": "release-it",
"test": "jest",
"test:watchAll": "jest --watchAll",
"test:clearCache": "jest --clearCache",
"_postinstall": "husky install",

@@ -93,26 +93,25 @@ "prepublishOnly": "pinst --disable",

"devDependencies": {
"@commitlint/cli": "11.0.0",
"@commitlint/config-conventional": "11.0.0",
"@release-it/conventional-changelog": "2.0.0",
"@commitlint/cli": "12.0.1",
"@commitlint/config-conventional": "12.0.1",
"@release-it/conventional-changelog": "2.0.1",
"@types/express": "4.17.11",
"@types/jest": "26.0.20",
"@types/jsonwebtoken": "8.5.0",
"@types/node": "14.14.31",
"@types/node": "14.14.32",
"@types/server-destroy": "1.0.1",
"axios": "0.21.1",
"express": "4.17.1",
"husky": "5.1.0",
"husky": "5.1.3",
"jest": "26.6.3",
"markdownlint-cli": "0.26.0",
"pinst": "2.1.4",
"markdownlint-cli": "0.27.1",
"pinst": "2.1.6",
"release-it": "14.4.1",
"rimraf": "3.0.2",
"server-destroy": "1.0.1",
"snazzy": "9.0.0",
"socket.io": "3.1.1",
"socket.io-client": "3.1.1",
"ts-jest": "26.5.1",
"socket.io": "3.1.2",
"socket.io-client": "3.1.2",
"ts-jest": "26.5.3",
"ts-standard": "10.0.0",
"typescript": "4.1.5"
"typescript": "4.2.3"
}
}

@@ -90,2 +90,28 @@ <h1 align="center">Thream/socketio-jwt</h1>

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

@@ -95,2 +121,3 @@

- `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.

@@ -124,3 +151,3 @@ ### Client side

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.

@@ -127,0 +154,0 @@ ## 📄 License

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc