@nitra/cf-security 3.3.1 → 3.3.2

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.
Files changed (2) hide show
  1. package/package.json +3 -2
  2. package/src/jwt-c.js +50 -0
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@nitra/cf-security",
3
- "version": "3.3.1",
3
+ "version": "3.3.2",
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,50 @@
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
+ // Читаємо кукі
12
+ const c = Object.fromEntries(req.raw.headers.cookie.split('; ').map(v => v.split(/=(.*)/s).map(decodeURIComponent)))
13
+
14
+ // Для дева можна й не передавати токен
15
+ if (isDev) {
16
+ // Але якщо передали - то беремо контент з нього
17
+ if (c['jwt-auth']) {
18
+ // ігноруючи expired
19
+ const token = await verify(c['jwt-auth'], { ignoreExpiration: true })
20
+ return token.body
21
+ } else {
22
+ return { name: 'dev', 'https://hasura.io/jwt/claims': { 'x-hasura-allowed-roles': allowedRoles } }
23
+ }
24
+ }
25
+
26
+ // Перевіряємо токен тільки
27
+ if (!c['jwt-auth']) {
28
+ throw new Error('[verification] no authorization header')
29
+ }
30
+
31
+ const token = await verify(c['jwt-auth'])
32
+
33
+ if (!token) {
34
+ throw new Error('[verification] invalid token')
35
+ }
36
+
37
+ const roleArray = token.body['https://hasura.io/jwt/claims']['x-hasura-allowed-roles']
38
+ const intersectRoles = intersection(roleArray, allowedRoles)
39
+
40
+ if (intersectRoles.length === 0) {
41
+ throw new Error(`[verification] unallowed roles ${roleArray}`)
42
+ }
43
+
44
+ return token.body
45
+ }
46
+
47
+ function intersection(a, b) {
48
+ const setA = new Set(a)
49
+ return b.filter(value => setA.has(value))
50
+ }