@opengis/fastify-table 1.1.44 → 1.1.46

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/Changelog.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # fastify-table
2
2
 
3
- ## 1.1.44 - 21.10.2024
3
+ ## 1.1.46 - 22.10.2024
4
4
 
5
5
  - addHook params refactor
6
6
  - add handlebars to utils
@@ -16,15 +16,16 @@ function checkXSS({ body, schema = {} }) {
16
16
  // escape arrows on non-RTE
17
17
  Object.keys(body)
18
18
  .filter((key) => ['<', '>'].find((el) => body[key]?.includes?.(el))
19
- && !['Summernote', 'Tiny', 'Ace'].includes(schema[key]?.type))
19
+ && !['Summernote', 'Tiny', 'Ace'].includes(schema?.[key]?.type))
20
20
  ?.forEach((key) => {
21
21
  Object.assign(body, { [key]: body[key].replace(/</g, '&lt;').replace(/>/g, '&gt;') });
22
22
  });
23
+
23
24
  // try { } catch (err) { return { error: err.toString() }; }
24
25
 
25
26
  if (!stopWords.length) return { body };
26
27
 
27
- const disabledCheckFields = Object.keys(schema)?.filter((el) => schema[el]?.xssCheck === false); // exclude specific columns
28
+ const disabledCheckFields = Object.keys(schema || {})?.filter((el) => schema?.[el]?.xssCheck === false); // exclude specific columns
28
29
 
29
30
  // check RTE
30
31
  /* const richTextFields = Object.keys(schema).filter((el) => ['Summernote', 'Tiny', 'Ace'].includes(schema[el]?.type));
@@ -20,19 +20,18 @@ left join admin.user_roles d on
20
20
  where $1 in (a.route_id, a.alias) and $2 in (b.user_uid, d.user_uid)`;
21
21
 
22
22
  export default async function getAccess({ table, id, user }) {
23
- if (config.auth?.disable || user?.user_type?.includes('admin')) {
24
- return { actions: ['get', 'edit', 'del'], my: true, query: '1=1' };
25
- }
26
-
27
23
  const { client: pg } = pgClients || {};
28
24
  const { uid, user_type: userType } = user || {};
29
25
 
30
- if (!uid || !table) return null;
31
-
32
- if (!pg.pk?.['admin.access']) return null;
26
+ if (!table || !pg.pk?.['admin.access']) return null;
33
27
 
34
28
  const body = await getTemplate('table', table) || {};
35
- if (!body?.table) return null;
29
+
30
+ if (config.auth?.disable || user?.user_type?.includes('admin') || body?.public) {
31
+ return { actions: ['get', 'edit', 'del'], my: true, query: '1=1' };
32
+ }
33
+
34
+ if (!uid || !body?.table) return null;
36
35
 
37
36
  const { scope = 'my', actions = [] } = await pg.query(q, [table, uid]).then((res) => res.rows?.[0] || {});
38
37
 
@@ -1,28 +1,4 @@
1
- function formatData(fieldType = 'text', value = null) {
2
- if (!value) return null;
3
- if (fieldType === 'geometry') {
4
- return typeof value === 'object' ? `st_astext(st_geomfromgeojson('${JSON.stringify(value)}'::json))` : `st_astext('${value}'::geometry)`;
5
- }
6
- if (['integer', 'numeric', 'double precision'].includes(fieldType)) {
7
- return value || null;
8
- }
9
- if (fieldType.includes('timestamp') || fieldType === 'date') {
10
- if (typeof value === 'object') {
11
- return value ? `'${value.toISOString()}'::${fieldType}` : null;
12
- }
13
- return value ? `'${value}'::${fieldType}` : null;
14
- }
15
- if (typeof value === 'object' || fieldType.includes('json')) {
16
- if (Array.isArray(value)) {
17
- return `'${JSON.stringify(value)}'`;
18
- }
19
- return `'${JSON.stringify(value)}'`;
20
- }
21
- if (Array.isArray(value)) {
22
- return `'{ ${value.join(',')} }'::${fieldType}`;
23
- }
24
- return `'${value || null}'`;
25
- }
1
+ import getMeta from '../../../pg/funcs/getMeta.js';
26
2
 
27
3
  export default async function logChanges({
28
4
  pg, table, id, data, uid = 1, type,
@@ -55,13 +31,23 @@ export default async function logChanges({
55
31
 
56
32
  const old = type !== 'INSERT' ? await pg.query(q, [id]).then((res) => res.rows?.[0] || {}) : {};
57
33
 
58
- const fieldTypes = fields?.reduce((acc, curr) => Object.assign(acc, { [curr.name]: pg.pgType[curr.dataTypeID] }), {}) || {};
59
- const q1 = Object.keys(data || {}).map((el) => `insert into log.table_changes_data(change_id,entity_key,value_old,value_new)
60
- values('${changeId}', '${el}', ${formatData(fieldTypes[el], old[el])}, ${formatData(fieldTypes[el], data[el])}) returning *`).join(';\n');
61
- // console.log(q1);
62
- const res = await pg.query(q1);
34
+ const { columns = [] } = await getMeta({ table: 'log.table_changes_data' });
35
+ const names = columns.map((el) => el.name);
36
+
37
+ const res = await Promise.all(Object.keys(data || {}).map(async (el) => {
38
+ const filterData = Object.entries({
39
+ change_id: changeId, entity_key: el, value_old: old[el], value_new: data[el], uid,
40
+ })
41
+ .filter((el) => el[1] && names.includes(el[0]));
42
+
43
+ const insertQuery = `insert into log.table_changes_data (${filterData?.map((key) => `"${key[0]}"`).join(',')})
44
+ values (${filterData?.map((key, i) => `$${i + 1}`).join(',')}) returning *`;
45
+
46
+ const { rows = [] } = await pg.query(insertQuery, [...filterData.map((el) => (el[1] && typeof el[1] === 'object' && (!Array.isArray(el[1]) || typeof el[1]?.[0] === 'object') ? JSON.stringify(el[1]) : el[1]))]) || {};
47
+ return rows[0];
48
+ }));
63
49
 
64
- const newData = type === 'DELETE' ? {} : (Array.isArray(res) ? res : [res]).reduce((acc, curr) => Object.assign(acc, { [curr.rows?.[0].entity_key]: curr.rows?.[0].value_new }), {});
50
+ const newData = type === 'DELETE' ? {} : (Array.isArray(res) ? res : [res]).reduce((acc, curr) => Object.assign(acc, { [curr.entity_key]: curr.value_new }), {});
65
51
  // console.log('logChanges OK', type);
66
52
  return {
67
53
  change_id: changeId, entity_type: table, entity_id: id, uid, change_type: type, old, new: newData,
@@ -2,7 +2,7 @@ import config from '../../config.js';
2
2
  import hookList from './hookList.js';
3
3
 
4
4
  export default async function applyHook(name, data) {
5
- const debug = config.local || config.debug;
5
+ const { debug } = config;
6
6
  if (debug) console.log('applyHook', name);
7
7
  if (!hookList[name]?.length) return null;
8
8
  const result = {};
@@ -1,4 +1,5 @@
1
1
  {
2
+ "public": true,
2
3
  "key": "rz_id",
3
4
  "table": "itree.rest_zones",
4
5
  "query": "verif",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengis/fastify-table",
3
- "version": "1.1.44",
3
+ "version": "1.1.46",
4
4
  "type": "module",
5
5
  "description": "core-plugins",
6
6
  "main": "index.js",
@@ -24,7 +24,8 @@ export default async function card(req) {
24
24
  table: hookData?.table || params.table,
25
25
  id: hookData?.id || params?.id,
26
26
  user,
27
- });
27
+ }) || {};
28
+
28
29
  if (!actions.includes('get') || (scope === 'my' && !my)) {
29
30
  return { message: 'access restricted', status: 403 };
30
31
  }
@@ -30,7 +30,8 @@ export default async function dataAPI(req) {
30
30
  table: hookData?.table || params.table,
31
31
  id: hookData?.id || params?.id,
32
32
  user,
33
- });
33
+ }) || {};
34
+
34
35
  if (!actions.includes('get') || (scope === 'my' && !my)) {
35
36
  return { message: 'access restricted', status: 403 };
36
37
  }
@@ -30,7 +30,8 @@ export default async function tableAPI(req) {
30
30
  table: hookData?.table || params.table,
31
31
  id: hookData?.id || params?.id,
32
32
  user,
33
- });
33
+ }) || {};
34
+
34
35
  if (!actions.includes('get') || (scope === 'my' && !my)) {
35
36
  return { message: 'access restricted', status: 403 };
36
37
  }
@@ -4,7 +4,22 @@ import assert from 'node:assert';
4
4
  import build from '../../helper.js';
5
5
 
6
6
  import setToken from '../../crud/funcs/setToken.js';
7
+ import getToken from '../../crud/funcs/getToken.js';
8
+ import addHook from '../../hook/funcs/addHook.js';
7
9
  import config from '../config.js';
10
+ import pgClients from '../../pg/pgClients.js';
11
+
12
+ addHook('preInsert', async ({ table }) => getToken({
13
+ mode: 'a', token: table, uid: '1', json: 1,
14
+ }));
15
+
16
+ addHook('preUpdate', async ({ table }) => getToken({
17
+ mode: 'w', token: table, uid: '1', json: 1,
18
+ }));
19
+
20
+ addHook('preDelete', async ({ table }) => getToken({
21
+ mode: 'w', token: table, uid: '1', json: 1,
22
+ }));
8
23
 
9
24
  test('api crud xss', async (t) => {
10
25
  const app = await build(t);
@@ -13,52 +28,53 @@ test('api crud xss', async (t) => {
13
28
  req.session = session;
14
29
  req.user = session.passport.user;
15
30
  });
16
- // app.decorateRequest('session', session);
17
31
 
32
+ const id = 'test';
18
33
  const prefix = config.prefix || '/api';
19
34
 
20
- let addTokens;
21
- let editTokens;
22
-
23
- // before
24
- t.test('setToken', async () => {
25
- addTokens = setToken({
26
- ids: [JSON.stringify({ table: 'gis.dataset', form: 'test.dataset.form' })],
35
+ await t.test('POST /insert', async () => {
36
+ const addTokens = setToken({
37
+ ids: [JSON.stringify({ table: 'test.rest_zone.table', form: 'rest_zone.form' })],
27
38
  mode: 'a',
28
39
  uid: 1,
29
40
  array: 1,
30
41
  });
31
- editTokens = setToken({
32
- ids: [JSON.stringify({ id: '5400000', table: 'gis.dataset', form: 'test.dataset.form' })],
33
- mode: 'w',
34
- uid: 1,
35
- array: 1,
36
- });
37
- assert.ok(addTokens.length === 1 && editTokens.length === 1, 'invalid token');
38
- });
39
-
40
- await t.test('POST /insert', async () => {
42
+ assert.ok(addTokens.length, 'invalid token');
41
43
  const res = await app.inject({
42
44
  method: 'POST',
43
45
  url: `${prefix}/table/${addTokens[0]}`,
44
- body: { dataset_name: '<a onClick="alert("XSS Injection")">xss injection</a>', dataset_id: '5400000' },
46
+ body: { rz_id: 'test', composition: '<a onClick="alert("XSS Injection")">xss injection</a>' },
45
47
  });
46
48
  assert.equal(res?.json()?.status || res?.statusCode, 409);
47
49
  });
48
50
 
51
+ const editTokens = setToken({
52
+ ids: [JSON.stringify({ id, table: 'test.rest_zone.table', form: 'rest_zone.form' })],
53
+ mode: 'w',
54
+ uid: 1,
55
+ array: 1,
56
+ });
57
+
49
58
  await t.test('PUT /update', async () => {
50
59
  const res = await app.inject({
51
60
  method: 'PUT',
52
- url: `${prefix}/table/${editTokens[0]}/${editTokens[0]}`,
53
- body: { editor_id: '11', dataset_name: '<a onClick="alert("XSS Injection")">xss injection</a>' },
61
+ url: `${prefix}/table/${editTokens[0]}`,
62
+ body: { editor_id: '11', composition: '<a onClick="alert("XSS Injection")">xss injection</a>' },
54
63
  });
55
64
  assert.equal(res.json()?.status || res?.statusCode, 409);
56
65
  });
57
66
  await t.test('DELETE /delete', async () => {
58
67
  const res = await app.inject({
59
68
  method: 'DELETE',
60
- url: `${prefix}/table/gis.dataset/5400000`,
69
+ url: `${prefix}/table/${editTokens[0]}`,
61
70
  });
62
71
  assert.equal(res?.json()?.status || res?.statusCode, 200);
63
72
  });
73
+
74
+ // after
75
+ await t.test('clean up', async () => {
76
+ const { rowCount } = await pgClients.client.query('delete from itree.rest_zones where composition::text ilike \'%xss injection%\'');
77
+ const { rowCount: testRows } = await pgClients.client.query('delete from itree.rest_zones where rz_id=\'test\'');
78
+ console.log('clean up', rowCount, testRows);
79
+ });
64
80
  });
@@ -11,6 +11,13 @@ const table = 'test.rest_zone.table';
11
11
 
12
12
  test('api table', async (t) => {
13
13
  const app = await build(t);
14
+
15
+ const session = { passport: { user: { uid: '1', user_type: 'admin' } } };
16
+ app.addHook('onRequest', async (req) => {
17
+ req.session = session;
18
+ req.user = session.passport.user;
19
+ });
20
+
14
21
  await init(pgClients.client);
15
22
 
16
23
  const body = await getTemplate('table', table);