@opengis/fastify-table 1.0.7 → 1.0.9

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 (59) hide show
  1. package/.eslintrc.cjs +42 -42
  2. package/Changelog.md +47 -0
  3. package/README.md +26 -26
  4. package/config.js +11 -3
  5. package/crud/controllers/deleteCrud.js +10 -10
  6. package/crud/controllers/insert.js +28 -9
  7. package/crud/controllers/update.js +29 -10
  8. package/crud/controllers/utils/checkXSS.js +45 -0
  9. package/crud/controllers/utils/xssInjection.js +72 -0
  10. package/crud/funcs/dataDelete.js +15 -15
  11. package/crud/funcs/dataInsert.js +24 -24
  12. package/crud/funcs/getIdByToken.js +29 -0
  13. package/crud/funcs/isFileExists.js +13 -13
  14. package/crud/funcs/setTokenById.js +55 -0
  15. package/helper.js +28 -28
  16. package/index.js +32 -22
  17. package/package.json +22 -22
  18. package/pg/funcs/autoIndex.js +89 -89
  19. package/pg/funcs/getMeta.js +27 -27
  20. package/pg/funcs/init.js +42 -42
  21. package/pg/funcs/pgClients.js +2 -2
  22. package/pg/index.js +35 -35
  23. package/pg/pgClients.js +17 -17
  24. package/policy/funcs/checkPolicy.js +74 -0
  25. package/policy/funcs/sqlInjection.js +33 -0
  26. package/policy/index.js +14 -0
  27. package/redis/client.js +8 -8
  28. package/redis/funcs/redisClients.js +2 -2
  29. package/redis/index.js +19 -19
  30. package/server/templates/form/test.dataset.form.json +412 -0
  31. package/server.js +14 -14
  32. package/table/controllers/data.js +55 -51
  33. package/table/controllers/filter.js +24 -24
  34. package/table/controllers/form.js +10 -10
  35. package/table/controllers/suggest.js +60 -60
  36. package/table/controllers/utils/getSelect.js +20 -20
  37. package/table/controllers/utils/getSelectMeta.js +66 -66
  38. package/table/funcs/getFilterSQL/index.js +75 -75
  39. package/table/funcs/getFilterSQL/util/formatValue.js +142 -142
  40. package/table/funcs/getFilterSQL/util/getCustomQuery.js +13 -13
  41. package/table/funcs/getFilterSQL/util/getFilterQuery.js +73 -73
  42. package/table/funcs/getFilterSQL/util/getOptimizedQuery.js +12 -12
  43. package/table/funcs/getFilterSQL/util/getTableSql.js +34 -34
  44. package/table/index.js +14 -14
  45. package/test/api/crud.test.js +50 -48
  46. package/test/api/crud.xss.test.js +70 -0
  47. package/test/api/table.test.js +49 -49
  48. package/test/config.example +18 -18
  49. package/test/funcs/crud.test.js +77 -51
  50. package/test/funcs/pg.test.js +32 -32
  51. package/test/funcs/redis.test.js +19 -19
  52. package/test/funcs/table.test.js +48 -48
  53. package/test/templates/cls/test.json +9 -9
  54. package/test/templates/form/cp_building.form.json +32 -32
  55. package/test/templates/select/account_id.json +3 -3
  56. package/test/templates/select/storage.data.json +2 -2
  57. package/test/templates/table/gis.dataset.table.json +20 -20
  58. package/test/templates/table/green_space.table.json +4 -4
  59. package/changelog.md +0 -26
package/index.js CHANGED
@@ -1,22 +1,32 @@
1
- // import pg from 'pg';
2
- import fp from 'fastify-plugin';
3
- import config from './config.js';
4
- // import rclient from './redis/client.js';
5
-
6
- import redisPlugin from './redis/index.js';
7
- import pgPlugin from './pg/index.js';
8
- import tablePlugin from './table/index.js';
9
- import crudPlugin from './crud/index.js';
10
-
11
- async function plugin(fastify, opt) {
12
- // console.log(opt);
13
- config.pg = opt.pg;
14
- config.redis = opt.redis;
15
-
16
- redisPlugin(fastify);
17
- await pgPlugin(fastify, opt);
18
- tablePlugin(fastify, opt);
19
- crudPlugin(fastify, opt);
20
- }
21
- export default fp(plugin);
22
- // export { rclient };
1
+ // import pg from 'pg';
2
+ import fp from 'fastify-plugin';
3
+ import config from './config.js';
4
+ // import rclient from './redis/client.js';
5
+
6
+ import redisPlugin from './redis/index.js';
7
+ import pgPlugin from './pg/index.js';
8
+ import tablePlugin from './table/index.js';
9
+ import crudPlugin from './crud/index.js';
10
+ import policyPlugin from './policy/index.js';
11
+
12
+ async function plugin(fastify, opt) {
13
+ // console.log(opt);
14
+ config.pg = opt.pg;
15
+ config.redis = opt.redis;
16
+
17
+ // independent npm start / unit test
18
+ if (!fastify.config) {
19
+ fastify.decorate('config', config);
20
+ }
21
+ if (!fastify.funcs) {
22
+ fastify.decorateRequest('funcs', fastify);
23
+ }
24
+
25
+ policyPlugin(fastify);
26
+ redisPlugin(fastify);
27
+ await pgPlugin(fastify, opt);
28
+ tablePlugin(fastify, opt);
29
+ crudPlugin(fastify, opt);
30
+ }
31
+ export default fp(plugin);
32
+ // export { rclient };
package/package.json CHANGED
@@ -1,23 +1,23 @@
1
- {
2
- "name": "@opengis/fastify-table",
3
- "version": "1.0.7",
4
- "type": "module",
5
- "description": "core-plugins",
6
- "main": "index.js",
7
- "scripts": {
8
- "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
9
- "test": "echo \"Error: no test specified\" && exit 1"
10
- },
11
- "dependencies": {
12
- "ioredis": "^5.3.2",
13
- "fastify": "^4.26.1",
14
- "fastify-plugin": "^4.0.0",
15
- "pg": "^8.11.3"
16
- },
17
- "devDependencies": {
18
- "eslint": "^8.49.0",
19
- "eslint-config-airbnb": "^19.0.4"
20
- },
21
- "author": "Softpro",
22
- "license": "ISC"
1
+ {
2
+ "name": "@opengis/fastify-table",
3
+ "version": "1.0.9",
4
+ "type": "module",
5
+ "description": "core-plugins",
6
+ "main": "index.js",
7
+ "scripts": {
8
+ "lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
9
+ "test": "echo \"Error: no test specified\" && exit 1"
10
+ },
11
+ "dependencies": {
12
+ "ioredis": "^5.3.2",
13
+ "fastify": "^4.26.1",
14
+ "fastify-plugin": "^4.0.0",
15
+ "pg": "^8.11.3"
16
+ },
17
+ "devDependencies": {
18
+ "eslint": "^8.49.0",
19
+ "eslint-config-airbnb": "^19.0.4"
20
+ },
21
+ "author": "Softpro",
22
+ "license": "ISC"
23
23
  }
@@ -1,89 +1,89 @@
1
- // const rclient = require('../../redis/client')
2
- import pgClient from '../pgClients.js';
3
-
4
- // subfunc
5
- const getTable = ({ table }) => table.toLowerCase().replace(/[\n\r]+/g, ' ').split(' from ')
6
- .filter((el) => /^[a-z0-9_]+\.[a-z0-9_]+/.test(el))
7
- .map((el) => el.split(/[ )]/)[0]);
8
-
9
- const loadedIndex = {};
10
-
11
- // main func
12
- async function autoIndex({ table, columns: filter, pg = pgClient.client }) {
13
- if (!filter?.length || !table) return null;
14
-
15
- const attrs = filter.map((el) => (el.name || el).replace(/'/g, '')).sort();
16
- const types = filter.map((el) => (el.name ? el : { name: el }))
17
- .reduce((p, el) => ({ ...p, [el.name]: el.type || '-' }), {});
18
-
19
- const redisKey = `autoindex1:${table}:${attrs.join(';')}`;
20
- const tableList = getTable({ table });
21
- const existsCache = loadedIndex[redisKey];
22
- if (existsCache) { return 'ok'; }
23
-
24
- const tbs = tableList[0];
25
- const [ns, tbl] = tableList[0].split('.');
26
- const { rows: index } = await pg.query(`select * from pg_indexes where tablename = '${tbl}' and schemaname = '${ns}'`);
27
-
28
- if (existsCache && index?.length > 0) { return null; }
29
- // console.log('autoindex', table, filter?.map((el) => el.name || el));
30
- const { rows: cols } = await pg.query(`SELECT attrelid::regclass AS tbl, attname AS aname, atttypid::regtype AS datatype, atttypid
31
- FROM pg_attribute WHERE attrelid = '${tbs}'::regclass and attname = any('{ ${attrs} }')`);
32
-
33
- const qIndex = [];
34
- const indexAr = {};
35
-
36
- // console.log(cols);
37
- for (let i = 0; i < cols.length; i += 1) {
38
- const el = cols[i];
39
- el.relname = tbl;
40
- el.nspname = ns;
41
-
42
- const indexUsing = (el.datatype === 'geometry' ? 'gist' : null)
43
- || (types[el.aname] === 'Text' || el.datatype?.includes('[]') ? 'gin' : null)
44
- || 'btree';
45
-
46
- const name = `${el.nspname}_${el.relname}_${el.aname}_${indexUsing}_idx`;
47
- const exists = index.filter((ind) => ind.tablename === el.relname && ind.schemaname === el.nspname && ind.indexdef.includes(types[el.aname] === 'Text'
48
- ? `gin (${el.aname} gin_trgm_ops)` : `btree (${el.aname})`));
49
-
50
- indexAr[el.aname] = {
51
- name, type: el.datatype, exists, // exists1,
52
- };
53
-
54
- // drop
55
- if (exists?.length > 1) {
56
- exists.filter((ind, i1) => i1).forEach((ind) => qIndex.push(`DROP INDEX if exists ${ind.schemaname}.${ind.indexname} `));
57
- }
58
-
59
- // add
60
- if (exists?.length === 0) {
61
- // console.log(`${name} - ${el.datatype}`);
62
-
63
- const suffix = types[el.aname] === 'Text' ? 'gin_trgm_ops' : '';
64
- if (['text'].includes(el?.datatype)) {
65
- qIndex.push(`CREATE INDEX if not exists ${name} ON ${el.nspname}.${el.relname} USING ${indexUsing} (${el.aname} ${suffix})`);
66
- }
67
- if (indexUsing === 'gist') {
68
- qIndex.push(`CREATE INDEX if not exists ${name.replace('gist', 'gist1')}
69
- ON ${el.nspname}.${el.relname} USING gist (${el.aname})`);
70
-
71
- qIndex.push(`CREATE INDEX if not exists ${name.replace('gist', 'area')}
72
- ON ${el.nspname}.${el.relname} USING btree (st_area(st_transform(${el.aname},3857)))`);
73
- qIndex.push(`CREATE INDEX if not exists ${name.replace('gist', '4326')}
74
- ON ${el.nspname}.${el.relname} USING gist (st_transform(${el.aname},4326))`);
75
- }
76
- }
77
- }
78
-
79
- loadedIndex[redisKey] = 1;
80
- // throw qIndex;
81
- if (!qIndex.length) return null;
82
-
83
- // console.log(qIndex.filter((v, i, a) => a.indexOf(v) === i));
84
- // logger.file('index', { table, filter, sql: qIndex.filter((v, i, a) => a.indexOf(v) === i) });
85
- qIndex.filter((v, i, a) => a.indexOf(v) === i).map((el) => pg.one(el).catch((err) => console.log(err.toString())));
86
- return 'ok';
87
- }
88
-
89
- export default autoIndex;
1
+ // const rclient = require('../../redis/client')
2
+ import pgClient from '../pgClients.js';
3
+
4
+ // subfunc
5
+ const getTable = ({ table }) => table.toLowerCase().replace(/[\n\r]+/g, ' ').split(' from ')
6
+ .filter((el) => /^[a-z0-9_]+\.[a-z0-9_]+/.test(el))
7
+ .map((el) => el.split(/[ )]/)[0]);
8
+
9
+ const loadedIndex = {};
10
+
11
+ // main func
12
+ async function autoIndex({ table, columns: filter, pg = pgClient.client }) {
13
+ if (!filter?.length || !table) return null;
14
+
15
+ const attrs = filter.map((el) => (el.name || el).replace(/'/g, '')).sort();
16
+ const types = filter.map((el) => (el.name ? el : { name: el }))
17
+ .reduce((p, el) => ({ ...p, [el.name]: el.type || '-' }), {});
18
+
19
+ const redisKey = `autoindex1:${table}:${attrs.join(';')}`;
20
+ const tableList = getTable({ table });
21
+ const existsCache = loadedIndex[redisKey];
22
+ if (existsCache) { return 'ok'; }
23
+
24
+ const tbs = tableList[0];
25
+ const [ns, tbl] = tableList[0].split('.');
26
+ const { rows: index } = await pg.query(`select * from pg_indexes where tablename = '${tbl}' and schemaname = '${ns}'`);
27
+
28
+ if (existsCache && index?.length > 0) { return null; }
29
+ // console.log('autoindex', table, filter?.map((el) => el.name || el));
30
+ const { rows: cols } = await pg.query(`SELECT attrelid::regclass AS tbl, attname AS aname, atttypid::regtype AS datatype, atttypid
31
+ FROM pg_attribute WHERE attrelid = '${tbs}'::regclass and attname = any('{ ${attrs} }')`);
32
+
33
+ const qIndex = [];
34
+ const indexAr = {};
35
+
36
+ // console.log(cols);
37
+ for (let i = 0; i < cols.length; i += 1) {
38
+ const el = cols[i];
39
+ el.relname = tbl;
40
+ el.nspname = ns;
41
+
42
+ const indexUsing = (el.datatype === 'geometry' ? 'gist' : null)
43
+ || (types[el.aname] === 'Text' || el.datatype?.includes('[]') ? 'gin' : null)
44
+ || 'btree';
45
+
46
+ const name = `${el.nspname}_${el.relname}_${el.aname}_${indexUsing}_idx`;
47
+ const exists = index.filter((ind) => ind.tablename === el.relname && ind.schemaname === el.nspname && ind.indexdef.includes(types[el.aname] === 'Text'
48
+ ? `gin (${el.aname} gin_trgm_ops)` : `btree (${el.aname})`));
49
+
50
+ indexAr[el.aname] = {
51
+ name, type: el.datatype, exists, // exists1,
52
+ };
53
+
54
+ // drop
55
+ if (exists?.length > 1) {
56
+ exists.filter((ind, i1) => i1).forEach((ind) => qIndex.push(`DROP INDEX if exists ${ind.schemaname}.${ind.indexname} `));
57
+ }
58
+
59
+ // add
60
+ if (exists?.length === 0) {
61
+ // console.log(`${name} - ${el.datatype}`);
62
+
63
+ const suffix = types[el.aname] === 'Text' ? 'gin_trgm_ops' : '';
64
+ if (['text'].includes(el?.datatype)) {
65
+ qIndex.push(`CREATE INDEX if not exists ${name} ON ${el.nspname}.${el.relname} USING ${indexUsing} (${el.aname} ${suffix})`);
66
+ }
67
+ if (indexUsing === 'gist') {
68
+ qIndex.push(`CREATE INDEX if not exists ${name.replace('gist', 'gist1')}
69
+ ON ${el.nspname}.${el.relname} USING gist (${el.aname})`);
70
+
71
+ qIndex.push(`CREATE INDEX if not exists ${name.replace('gist', 'area')}
72
+ ON ${el.nspname}.${el.relname} USING btree (st_area(st_transform(${el.aname},3857)))`);
73
+ qIndex.push(`CREATE INDEX if not exists ${name.replace('gist', '4326')}
74
+ ON ${el.nspname}.${el.relname} USING gist (st_transform(${el.aname},4326))`);
75
+ }
76
+ }
77
+ }
78
+
79
+ loadedIndex[redisKey] = 1;
80
+ // throw qIndex;
81
+ if (!qIndex.length) return null;
82
+
83
+ // console.log(qIndex.filter((v, i, a) => a.indexOf(v) === i));
84
+ // logger.file('index', { table, filter, sql: qIndex.filter((v, i, a) => a.indexOf(v) === i) });
85
+ qIndex.filter((v, i, a) => a.indexOf(v) === i).map((el) => pg.one(el).catch((err) => console.log(err.toString())));
86
+ return 'ok';
87
+ }
88
+
89
+ export default autoIndex;
@@ -1,27 +1,27 @@
1
- // import pgClient from '../pgClients.js';
2
- import getPG from './getPG.js';
3
-
4
- const data = {};
5
-
6
- // decorator
7
- export default async function getMeta(opt) {
8
- const pg = opt.pg || getPG({ name: 'client' });
9
- const table = opt.table || opt;
10
-
11
- if (data[table]) return data[table];
12
-
13
- if (!pg.tlist.includes(table)) {
14
- return { error: `${table} - not found`, status: 400 };
15
- }
16
-
17
- const { fields } = await pg.query(`select * from ${table} where $1=$1 limit 0`, [1]);
18
- const { pks1 } = await pg.one(`SELECT json_object_agg(c.conrelid::regclass, a.attname) as pks1 FROM pg_constraint c
19
- left join pg_attribute a on c.conrelid=a.attrelid and a.attnum = c.conkey[1] WHERE c.contype='p'::"char"`, { cache: 0 });
20
- const pk = pks1[table];
21
-
22
- const geomAttr = fields.find((el) => pg.pgType[el.dataTypeID] === 'geometry')?.name; // change geometry text to geometry code
23
-
24
- const res = { pk, columns: fields, geom: geomAttr };
25
- data[table] = res;
26
- return res;
27
- }
1
+ // import pgClient from '../pgClients.js';
2
+ import getPG from './getPG.js';
3
+
4
+ const data = {};
5
+
6
+ // decorator
7
+ export default async function getMeta(opt) {
8
+ const pg = opt.pg || getPG({ name: 'client' });
9
+ const table = opt.table || opt;
10
+
11
+ if (data[table]) return data[table];
12
+
13
+ if (!pg.tlist.includes(table)) {
14
+ return { error: `${table} - not found`, status: 400 };
15
+ }
16
+
17
+ const { fields } = await pg.query(`select * from ${table} where $1=$1 limit 0`, [1]);
18
+ const { pks1 } = await pg.one(`SELECT json_object_agg(c.conrelid::regclass, a.attname) as pks1 FROM pg_constraint c
19
+ left join pg_attribute a on c.conrelid=a.attrelid and a.attnum = c.conkey[1] WHERE c.contype='p'::"char"`, { cache: 0 });
20
+ const pk = pks1[table];
21
+
22
+ const geomAttr = fields.find((el) => pg.pgType[el.dataTypeID] === 'geometry')?.name; // change geometry text to geometry code
23
+
24
+ const res = { pk, columns: fields, geom: geomAttr };
25
+ data[table] = res;
26
+ return res;
27
+ }
package/pg/funcs/init.js CHANGED
@@ -1,42 +1,42 @@
1
- import crypto from 'crypto';
2
-
3
- // import pg from 'pg';
4
- import getRedis from '../../redis/funcs/getRedis.js';
5
- // import config from '../config.js';
6
-
7
- async function init(client) {
8
- const textQuery = `select
9
- (select json_object_agg(conrelid::regclass ,(SELECT attname FROM pg_attribute WHERE attrelid = c.conrelid and attnum = c.conkey[1]))
10
- from pg_constraint c where contype='p' and connamespace::regnamespace::text not in ('sde')) as pk,
11
- (SELECT json_object_agg(t.oid::text,pg_catalog.format_type(t.oid, NULL)) FROM pg_catalog.pg_type t) as "pgType"`;
12
- const { pgType, pk } = await client.query(textQuery).then((d) => d.rows[0]);
13
-
14
- const tlist = await client.query(`select array_agg((select nspname from pg_namespace where oid=relnamespace)||'.'||relname) tlist
15
- from pg_class where relkind in ('r','v')`).then((d) => d.rows[0].tlist);
16
-
17
- async function one(query, param = {}) {
18
- const data = await client.query(query, Array.isArray(param) ? param : param.args || []);
19
- const result = ((Array.isArray(data) ? data.pop() : data)?.rows || [])[0] || {};
20
- return result;
21
- }
22
-
23
- async function queryCache(query) {
24
- const rclient = getRedis({ db: 0 })
25
- const hash = crypto.createHash('sha1').update(query).digest('base64');
26
- const keyCache = `pg:${hash}`;
27
- const cache = await rclient.get(keyCache);
28
- if (cache) {
29
- return JSON.parse(cache);
30
- }
31
- const data = await client.query(query);
32
- rclient.set(keyCache, JSON.stringify(data), 'EX', 60 * 60);
33
- return data;
34
- }
35
-
36
- Object.assign(client, {
37
- one, pgType, pk, tlist, queryCache,
38
- });
39
- }
40
-
41
- // export default client;
42
- export default init;
1
+ import crypto from 'crypto';
2
+
3
+ // import pg from 'pg';
4
+ import getRedis from '../../redis/funcs/getRedis.js';
5
+ // import config from '../config.js';
6
+
7
+ async function init(client) {
8
+ const textQuery = `select
9
+ (select json_object_agg(conrelid::regclass ,(SELECT attname FROM pg_attribute WHERE attrelid = c.conrelid and attnum = c.conkey[1]))
10
+ from pg_constraint c where contype='p' and connamespace::regnamespace::text not in ('sde')) as pk,
11
+ (SELECT json_object_agg(t.oid::text,pg_catalog.format_type(t.oid, NULL)) FROM pg_catalog.pg_type t) as "pgType"`;
12
+ const { pgType, pk } = await client.query(textQuery).then((d) => d.rows[0]);
13
+
14
+ const tlist = await client.query(`select array_agg((select nspname from pg_namespace where oid=relnamespace)||'.'||relname) tlist
15
+ from pg_class where relkind in ('r','v')`).then((d) => d.rows[0].tlist);
16
+
17
+ async function one(query, param = {}) {
18
+ const data = await client.query(query, Array.isArray(param) ? param : param.args || []);
19
+ const result = ((Array.isArray(data) ? data.pop() : data)?.rows || [])[0] || {};
20
+ return result;
21
+ }
22
+
23
+ async function queryCache(query) {
24
+ const rclient = getRedis({ db: 0 })
25
+ const hash = crypto.createHash('sha1').update(query).digest('base64');
26
+ const keyCache = `pg:${hash}`;
27
+ const cache = await rclient.get(keyCache);
28
+ if (cache) {
29
+ return JSON.parse(cache);
30
+ }
31
+ const data = await client.query(query);
32
+ rclient.set(keyCache, JSON.stringify(data), 'EX', 60 * 60);
33
+ return data;
34
+ }
35
+
36
+ Object.assign(client, {
37
+ one, pgType, pk, tlist, queryCache,
38
+ });
39
+ }
40
+
41
+ // export default client;
42
+ export default init;
@@ -1,2 +1,2 @@
1
- const pgClients = {};
2
- export default pgClients;
1
+ const pgClients = {};
2
+ export default pgClients;
package/pg/index.js CHANGED
@@ -1,35 +1,35 @@
1
- // import fp from 'fastify-plugin';
2
- //import pg from 'pg';
3
- import pgClients from './funcs/pgClients.js';
4
- import init from './funcs/init.js';
5
- import autoIndex from './funcs/autoIndex.js';
6
- import getMeta from './funcs/getMeta.js';
7
- import getPG from './funcs/getPG.js';
8
-
9
- function close() {
10
- // console.log('pg close');
11
- Object.keys(pgClients).forEach((el) => {
12
- // console.log(el);
13
- pgClients[el].end();
14
- });
15
-
16
- // return pgClients.client.end();
17
- }
18
-
19
- async function plugin(fastify, config) {
20
- const client = getPG({ ...config.pg || {}, name: 'client' })
21
- await init(client);
22
- fastify.addHook('onRequest', async (req) => {
23
- // req.funcs = fastify;
24
- req.pg = client;
25
- });
26
- //pgClients.client = client;
27
-
28
- // fastify.decorate('pg', client);
29
- fastify.decorate('autoIndex', autoIndex);
30
- fastify.decorate('getMeta', getMeta);
31
- fastify.decorate('getPG', getPG);
32
- fastify.addHook('onClose', close);
33
- }
34
-
35
- export default plugin;
1
+ // import fp from 'fastify-plugin';
2
+ //import pg from 'pg';
3
+ import pgClients from './funcs/pgClients.js';
4
+ import init from './funcs/init.js';
5
+ import autoIndex from './funcs/autoIndex.js';
6
+ import getMeta from './funcs/getMeta.js';
7
+ import getPG from './funcs/getPG.js';
8
+
9
+ function close() {
10
+ // console.log('pg close');
11
+ Object.keys(pgClients).forEach((el) => {
12
+ // console.log(el);
13
+ pgClients[el].end();
14
+ });
15
+
16
+ // return pgClients.client.end();
17
+ }
18
+
19
+ async function plugin(fastify, config) {
20
+ const client = getPG({ ...config.pg || {}, name: 'client' })
21
+ await init(client);
22
+ fastify.addHook('onRequest', async (req) => {
23
+ // req.funcs = fastify;
24
+ req.pg = client;
25
+ });
26
+ //pgClients.client = client;
27
+
28
+ // fastify.decorate('pg', client);
29
+ fastify.decorate('autoIndex', autoIndex);
30
+ fastify.decorate('getMeta', getMeta);
31
+ fastify.decorate('getPG', getPG);
32
+ fastify.addHook('onClose', close);
33
+ }
34
+
35
+ export default plugin;
package/pg/pgClients.js CHANGED
@@ -1,17 +1,17 @@
1
- import pg from 'pg';
2
- import config from '../config.js';
3
- import init from './funcs/init.js';
4
-
5
- const pgClients = {};
6
- if (config.pg) {
7
- const client = new pg.Pool({
8
- host: config.pg?.host || '127.0.0.1',
9
- port: config.pg?.port || 5432,
10
- database: config.pg?.database || 'postgres',
11
- user: config.pg?.user || 'postgres',
12
- password: config.pg?.password || 'postgres',
13
- });
14
- await init(client);
15
- pgClients.client = client;
16
- }
17
- export default pgClients;
1
+ import pg from 'pg';
2
+ import config from '../config.js';
3
+ import init from './funcs/init.js';
4
+
5
+ const pgClients = {};
6
+ if (config.pg) {
7
+ const client = new pg.Pool({
8
+ host: config.pg?.host || '127.0.0.1',
9
+ port: config.pg?.port || 5432,
10
+ database: config.pg?.database || 'postgres',
11
+ user: config.pg?.user || 'postgres',
12
+ password: config.pg?.password || 'postgres',
13
+ });
14
+ await init(client);
15
+ pgClients.client = client;
16
+ }
17
+ export default pgClients;
@@ -0,0 +1,74 @@
1
+ import block from './sqlInjection.js';
2
+
3
+ /**
4
+ * Middleware func
5
+ *
6
+ * @type function
7
+ * @alias checkPolicy
8
+ * @summary Функція дозволяє налаштувати доступ до сайту або API для адмін. та публічної частини веб-ресурсу
9
+ * @param {String} path - назва апі
10
+ * @returns {object|null} Returns object
11
+ */
12
+
13
+ export default function checkPolicy(req) {
14
+ const {
15
+ originalUrl: path, hostname, query, params, headers: hs, log, sid = 35, funcs = {},
16
+ } = req;
17
+ const user = req.user || req.session?.passport?.user;
18
+
19
+ const { config } = funcs;
20
+ const isUser = config.debug || !!user;
21
+
22
+ const isServer = process.argv[2];
23
+ const { policy = [] } = req.routeOptions?.config || {};
24
+
25
+ /*= == 1.File injection === */
26
+ if (JSON.stringify(params || {})?.includes('../') || JSON.stringify(query || {})?.includes('../') || path?.includes('../')) {
27
+ log.warn({
28
+ name: 'injection/file', params, query, message: 'access restricted: 1',
29
+ });
30
+ return { message: 'access restricted: 1', status: 403 };
31
+ }
32
+
33
+ /*= == 1.1 File === */
34
+ const allowExtPublic = ['.png', '.jpg', '.svg'];
35
+ const ext = path.toLowerCase().substr(-4);
36
+ if (path.includes('files/') && allowExtPublic.includes(ext)) return null;
37
+
38
+ /*= == 2.SQL Injection policy: no-sql === */
39
+ if (!policy.includes('no-sql')) {
40
+ const stopWords = block.filter((el) => path.includes(el));
41
+ if (stopWords?.length) {
42
+ log.warn({ name: 'injection/sql', stopWords, message: 'access restricted: 2' });
43
+ return { message: 'access restricted: 2', status: 403 };
44
+ }
45
+ }
46
+ /* Check is Not API */
47
+ const isApi = ['/files/', '/api/format/', '/api-user/', '/logger', '/file/'].filter((el) => path.includes(el)).length;
48
+ if (!isApi) return null;
49
+
50
+ /*= == 3. policy: referer === */
51
+ if (!hs?.referer?.includes?.(hostname) && policy.includes('referer') && !config.local && !config.debug) {
52
+ log.warn({ name: 'referer', message: 'access restricted: 3' });
53
+ return { message: 'access restricted: 3', status: 403 };
54
+ }
55
+
56
+ /*= == policy: public === */
57
+ if (policy.includes('public')) {
58
+ return null;
59
+ }
60
+
61
+ /*= == 4. policy: site auth === */
62
+ if (!policy.includes('site') && sid === 1 && isUser && !config.local && !config.debug) {
63
+ log.warn({ name: 'site', message: 'access restricted: 4' });
64
+ return { message: 'access restricted: 4', status: 403 };
65
+ }
66
+
67
+ /*= == 5. base policy: block api === */
68
+ if (sid === 35 && !isUser && isServer && !config.local && !config.debug) {
69
+ log.warn({ name: 'api', message: 'access restricted: 5' });
70
+ return { message: 'access restricted: 5', status: 403 };
71
+ }
72
+
73
+ return null;
74
+ }
@@ -0,0 +1,33 @@
1
+ const sqlInjection = [
2
+ '()',
3
+ '^',
4
+ '*',
5
+ 'like ',
6
+ '@variable',
7
+ '@@variable',
8
+ 'group by ',
9
+ 'union ',
10
+ 'select ',
11
+ 'having ',
12
+ 'as injectx',
13
+ 'where ',
14
+ 'rlike ',
15
+ 'if(',
16
+ 'sleep(',
17
+ 'waitfor delay',
18
+ 'benchmark(',
19
+ 'pg_sleep(',
20
+ "'\\\"",
21
+ 'randomblob(',
22
+ 'order by ',
23
+ 'union all ',
24
+ '+or',
25
+ 'or ',
26
+ 'and ',
27
+ "'' ",
28
+ '""" ',
29
+ '<script',
30
+ 'javascript:',
31
+ ]
32
+
33
+ export default sqlInjection;
@@ -0,0 +1,14 @@
1
+ // import fp from 'fastify-plugin';
2
+
3
+ import checkPolicy from './funcs/checkPolicy.js';
4
+
5
+ async function plugin(fastify) {
6
+ fastify.addHook('onRequest', async (request, reply) => {
7
+ const hookData = checkPolicy(request);
8
+ if (hookData?.status && hookData?.message) {
9
+ return reply.status(hookData?.status).send(hookData.message);
10
+ }
11
+ });
12
+ }
13
+
14
+ export default plugin;