@nitra/cf-security 3.3.1 → 3.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -2
- package/src/jwt-c.js +54 -0
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nitra/cf-security",
|
|
3
|
-
"version": "3.3.
|
|
3
|
+
"version": "3.3.3",
|
|
4
4
|
"description": "check header in cloud functions",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": "./src/index.js",
|
|
8
|
-
"./jwt": "./src/jwt.js"
|
|
8
|
+
"./jwt": "./src/jwt.js",
|
|
9
|
+
"./jwt-c": "./src/jwt-c.js"
|
|
9
10
|
},
|
|
10
11
|
"scripts": {
|
|
11
12
|
"test": "env $(cat ./test/.env) npx coverage-node test/index.js"
|
package/src/jwt-c.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import verify from '@nitra/jwt/verify'
|
|
2
|
+
import { isDev } from '@nitra/isenv'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Check request for Nitra security з токеном в кукі
|
|
6
|
+
*
|
|
7
|
+
* @param {object} req - Fastify Request for check
|
|
8
|
+
* @return {string} token if check passed
|
|
9
|
+
*/
|
|
10
|
+
export default async (req, allowedRoles) => {
|
|
11
|
+
if (!req.raw.headers?.cookie) {
|
|
12
|
+
throw new Error('[verification] missing cookie')
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Читаємо кукі
|
|
16
|
+
const c = Object.fromEntries(req.raw.headers.cookie.split('; ').map(v => v.split(/=(.*)/s).map(decodeURIComponent)))
|
|
17
|
+
|
|
18
|
+
// Для дева можна й не передавати токен
|
|
19
|
+
if (isDev) {
|
|
20
|
+
// Але якщо передали - то беремо контент з нього
|
|
21
|
+
if (c.__session) {
|
|
22
|
+
// ігноруючи expired
|
|
23
|
+
const token = await verify(c.__session, { ignoreExpiration: true })
|
|
24
|
+
return token.body
|
|
25
|
+
} else {
|
|
26
|
+
return { name: 'dev', 'https://hasura.io/jwt/claims': { 'x-hasura-allowed-roles': allowedRoles } }
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Перевіряємо токен тільки
|
|
31
|
+
if (!c.__session) {
|
|
32
|
+
throw new Error('[verification] no authorization header')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const token = await verify(c.__session)
|
|
36
|
+
|
|
37
|
+
if (!token) {
|
|
38
|
+
throw new Error('[verification] invalid token')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const roleArray = token.body['https://hasura.io/jwt/claims']['x-hasura-allowed-roles']
|
|
42
|
+
const intersectRoles = intersection(roleArray, allowedRoles)
|
|
43
|
+
|
|
44
|
+
if (intersectRoles.length === 0) {
|
|
45
|
+
throw new Error(`[verification] unallowed roles ${roleArray}`)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return token.body
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function intersection(a, b) {
|
|
52
|
+
const setA = new Set(a)
|
|
53
|
+
return b.filter(value => setA.has(value))
|
|
54
|
+
}
|