Compare commits

..

5 Commits

Author SHA1 Message Date
yutent f7542ecab3 更新package.json 2025-01-06 10:56:51 +08:00
yutent bd5c69c7dc 更新依赖 2025-01-06 10:53:20 +08:00
yutent 7e29408bdf 更新导出结构; 增加index.d.ts声明 2025-01-06 10:52:59 +08:00
yutent f0058ae87b 增加index.d.ts文件 2025-01-02 12:13:27 +08:00
yutent 0cd03ccde9 crypto.js升级为最新版 2023-11-01 14:33:57 +08:00
3 changed files with 108 additions and 80 deletions

21
index.d.ts vendored Normal file
View File

@ -0,0 +1,21 @@
declare module '@gm5/jwt' {
//
interface JwtConfig {
secret: string
ttl?: number
level?: number
}
interface JwtInstance {
ttl: number
sign(data: object, secret: string): string
verify(token: string, secret: string): object | false
}
interface JwtModule {
name: 'jwt'
install(conf?: JwtConfig): JwtInstance
}
export function createJwt(): JwtModule
}

154
index.js
View File

@ -4,8 +4,7 @@
* @date 2020/09/16 17:23:52
*/
import crypto from 'crypto.js'
import { base64encode, base64decode, sha1 } from 'crypto.js'
import { base64encode, base64decode, hmac, sha1 } from 'crypto.js'
const HS256_HEADER = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
const DEFAULT_CONFIG = {
@ -14,94 +13,95 @@ const DEFAULT_CONFIG = {
secret: 'it_is_secret_key' // jwt密钥, 使用时请修改
}
function hmac(str, secret) {
let buf = crypto.hmac('sha256', str, secret, 'buffer')
function hmac_base64(str, secret) {
let buf = hmac('sha256', str, secret, 'buffer')
return base64encode(buf, true)
}
export const JwtModule = {
name: 'jwt',
install(conf = {}) {
if (!conf.secret) {
console.warn(
new Error(
'Please make sure to set the `secret` field, as the default value is not secure'
function JwtMiddleware(req, res, next) {
let { secret, level } = this.get('jwt')
let deviceID = ''
let ssid
// options请求不处理jwt
if (req.method === 'OPTIONS') {
return next()
}
// 校验UA
if (level & 2) {
deviceID += req.header('user-agent')
}
// 校验IP
if (level & 4) {
deviceID += req.ip()
}
if (deviceID) {
deviceID = sha1(deviceID)
}
req.__mix_key__ = secret + deviceID
next()
}
export function createJwt() {
return {
name: 'jwt',
install(conf = {}) {
if (!conf.secret) {
console.warn(
new Error(
'You must set a `secret` key for jwt, or it will use the default key.'
)
)
)
}
}
let jwt = Object.assign({}, DEFAULT_CONFIG, conf)
this.set({ jwt })
let jwt = Object.assign({}, DEFAULT_CONFIG, conf)
this.set({ jwt })
this.use(JwtMiddleware)
return {
ttl: jwt.ttl,
// 签名, 返回token
// header: base64("{"typ":"JWT","alg":"HS256"}")
// 这里固定使用sha256
sign(data, secret) {
// 加入过期时间,
let payload = { data, expires: Date.now() + this.ttl * 1000 }
let token = ''
return {
ttl: jwt.ttl,
// 签名, 返回token
// header: base64("{"typ":"JWT","alg":"HS256"}")
// 这里固定使用sha256
sign(data, secret) {
// 加入过期时间,
let payload = { data, expires: Date.now() + this.ttl * 1000 }
let token = ''
payload = base64encode(JSON.stringify(payload), true)
token = hmac(`${HS256_HEADER}.${payload}`, secret)
payload = base64encode(JSON.stringify(payload), true)
token = hmac_base64(`${HS256_HEADER}.${payload}`, secret)
return `${HS256_HEADER}.${payload}.${token}`
},
return `${HS256_HEADER}.${payload}.${token}`
},
// 校验token
verify(token = '', secret) {
let jwt = token.split('.')
let auth, payload
// 校验token
verify(token = '', secret) {
let jwt = token.split('.')
let [_, payload, auth] = jwt
if (jwt.length !== 3) {
return false
}
payload = JSON.parse(base64decode(payload, true))
// 如果已经过期, 则不再校验hash
if (payload.expires < Date.now()) {
return false
}
if (hmac_base64(jwt.join('.'), secret) === auth) {
return payload.data
}
if (jwt.length !== 3) {
return false
}
auth = jwt.pop()
payload = JSON.parse(base64decode(jwt[1], true))
// 如果已经过期, 则不再校验hash
if (payload.expires < Date.now()) {
return false
}
if (hmac(jwt.join('.'), secret) === auth) {
return payload.data
}
return false
}
}
}
}
export function createJwt() {
return function (req, res, next) {
let { secret, level } = this.get('jwt')
let deviceID = ''
let ssid
// options请求不处理jwt
if (req.method === 'OPTIONS') {
return next()
}
// 校验UA
if (level & 2) {
deviceID += req.header('user-agent')
}
// 校验IP
if (level & 4) {
deviceID += req.ip()
}
if (deviceID) {
deviceID = sha1(deviceID)
}
req.__mix_key__ = secret + deviceID
next()
}
}

View File

@ -1,9 +1,10 @@
{
"name": "@gm5/jwt",
"version": "2.0.1",
"version": "3.0.1",
"type": "module",
"description": "json web token",
"main": "index.js",
"types": "index.d.ts",
"author": "yutent",
"keywords": [
"fivejs",
@ -12,9 +13,15 @@
"http",
"json_web_token"
],
"repository": "https://git.wkit.fun/gm5/jwt.git",
"repository": {
"type": "git",
"url": "https://git.wkit.fun/gm5/jwt.git"
},
"license": "MIT",
"dependencies": {
"crypto.js": "^2.0.1"
"crypto.js": "^3.3.4"
},
"engines": {
"node": ">=16.0.0"
}
}