anote-server-libs 0.9.5 → 0.9.7

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.
@@ -23,34 +23,34 @@ class BaseModelRepository {
23
23
  this.Migration = new Migration_1.MigrationRepository(db, dbMssql, logger);
24
24
  this.ApiCall = new ApiCall_1.ApiCallRepository(db, dbMssql, logger);
25
25
  }
26
- migrate(migrationsPath, callback, onlyAboveOrEquals = 0) {
26
+ migrate(migrationsPath, callback, onlyAboveOrEquals, onlyBelow) {
27
27
  (this.db ? Promise.all([
28
- this.db.query(`CREATE TABLE IF NOT EXISTS migration (
29
- id integer PRIMARY KEY,
30
- hash text NOT NULL,
31
- "sqlUp" text NOT NULL,
32
- "sqlDown" text NOT NULL,
33
- state integer NOT NULL,
34
- skip boolean NOT NULL
28
+ this.db.query(`CREATE TABLE IF NOT EXISTS migration (
29
+ id integer PRIMARY KEY,
30
+ hash text NOT NULL,
31
+ "sqlUp" text NOT NULL,
32
+ "sqlDown" text NOT NULL,
33
+ state integer NOT NULL,
34
+ skip boolean NOT NULL
35
35
  )`),
36
36
  this.db.query(`ALTER TABLE migration ADD COLUMN IF NOT EXISTS skip BOOLEAN NOT NULL DEFAULT FALSE`)
37
37
  ]) : Promise.all([
38
- this.dbMssql.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name=\'migration\' AND xtype=\'U\') CREATE TABLE migration (
39
- id int PRIMARY KEY,
40
- hash text NOT NULL,
41
- "sqlUp" text NOT NULL,
42
- "sqlDown" text NOT NULL,
43
- state int NOT NULL,
44
- skip bit NOT NULL
38
+ this.dbMssql.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name=\'migration\' AND xtype=\'U\') CREATE TABLE migration (
39
+ id int PRIMARY KEY,
40
+ hash text NOT NULL,
41
+ "sqlUp" text NOT NULL,
42
+ "sqlDown" text NOT NULL,
43
+ state int NOT NULL,
44
+ skip bit NOT NULL
45
45
  )`),
46
- this.dbMssql.query(`IF NOT EXISTS (
47
- SELECT *
48
- FROM INFORMATION_SCHEMA.COLUMNS
49
- WHERE TABLE_NAME = 'migration'
50
- AND COLUMN_NAME = 'skip'
51
- )
52
- BEGIN
53
- ALTER TABLE migration ADD skip BIT NOT NULL DEFAULT 0;
46
+ this.dbMssql.query(`IF NOT EXISTS (
47
+ SELECT *
48
+ FROM INFORMATION_SCHEMA.COLUMNS
49
+ WHERE TABLE_NAME = 'migration'
50
+ AND COLUMN_NAME = 'skip'
51
+ )
52
+ BEGIN
53
+ ALTER TABLE migration ADD skip BIT NOT NULL DEFAULT 0;
54
54
  END`)
55
55
  ])).then(() => {
56
56
  this.Migration.getAllBy('id').then((migrations) => {
@@ -70,16 +70,26 @@ END`)
70
70
  hash: crypto.createHash('sha256').update(content).digest('hex')
71
71
  };
72
72
  });
73
- if (migrationsAvailable.length === 0
74
- || migrationsAvailable.length
75
- !== migrationsAvailable[migrationsAvailable.length - 1].id)
73
+ const minAvailableId = migrationsAvailable.length > 0 ? migrationsAvailable[0].id : 0;
74
+ const maxAvailableId = migrationsAvailable.length > 0 ? migrationsAvailable[migrationsAvailable.length - 1].id : Infinity;
75
+ migrations = migrations.filter(m => m.id >= minAvailableId && m.id <= maxAvailableId);
76
+ if (onlyAboveOrEquals)
77
+ migrations = migrations.filter(m => m.id >= onlyAboveOrEquals);
78
+ if (onlyBelow)
79
+ migrations = migrations.filter(m => m.id < onlyBelow);
80
+ if (migrationsAvailable.length === 0 && migrations.length === 0)
76
81
  process.exit(5);
77
- let highestCommon = onlyAboveOrEquals;
78
- while (highestCommon < migrations.length && highestCommon < migrationsAvailable.length
82
+ if (migrationsAvailable.length && migrationsAvailable.length !== (migrationsAvailable[migrationsAvailable.length - 1].id - migrationsAvailable[0].id + 1))
83
+ process.exit(5);
84
+ let highestCommon = 0;
85
+ while (highestCommon < migrations.length
86
+ && highestCommon < migrationsAvailable.length
87
+ && migrations[highestCommon]
88
+ && migrationsAvailable[highestCommon]
79
89
  && migrations[highestCommon].hash === migrationsAvailable[highestCommon].hash)
80
90
  highestCommon++;
81
- this.applyDownUntil(migrations, migrations.length, highestCommon).then(highestCommon => {
82
- this.applyUpUntil(migrationsAvailable, Math.min(highestCommon, migrations.length), migrationsAvailable.length).then(callback, process.exit);
91
+ this.applyDownUntil(migrations, migrations.length, highestCommon).then(appliedId => {
92
+ this.applyUpUntil(migrationsAvailable, Math.min(appliedId, migrations.length), migrationsAvailable.length).then(callback, process.exit);
83
93
  }, process.exit);
84
94
  });
85
95
  }, () => process.exit(3));
@@ -91,8 +101,10 @@ END`)
91
101
  return Promise.all(tables.map(t => client.request().query('SELECT id FROM ' + t.table + ' WITH (UPDLOCK)')));
92
102
  }
93
103
  applyUpUntil(migrations, current, until) {
94
- if (current < until)
104
+ if (current < until) {
105
+ console.log('Applying migration ' + migrations[current].id);
95
106
  return this.applyUp(migrations[current]).then(() => this.applyUpUntil(migrations, current + 1, until));
107
+ }
96
108
  return Promise.resolve();
97
109
  }
98
110
  applyUp(migration) {
@@ -126,6 +138,7 @@ END`)
126
138
  applyDownUntil(migrations, current, until) {
127
139
  if (current > until && !migrations[current - 1]?.skip) {
128
140
  current--;
141
+ console.log('Reverting migration ' + migrations[current].id);
129
142
  return this.applyDown(migrations[current]).then(() => this.applyDownUntil(migrations, current, until));
130
143
  }
131
144
  return Promise.resolve(current);
@@ -1,168 +1,178 @@
1
- import * as crypto from 'crypto';
2
- import * as fs from 'fs';
3
- import * as Memcached from 'memcached';
4
- import {ConnectionPool, Transaction} from 'mssql';
5
- import {ClientBase, Pool} from 'pg';
6
- import {Logger} from 'winston';
7
- import { ApiCallRepository } from '../ApiCall';
8
- import { Migration, MigrationRepository } from '../Migration';
9
- import {ModelRepr} from './ModelDao';
10
-
11
- export class BaseModelRepository {
12
- Migration: MigrationRepository;
13
- ApiCall: ApiCallRepository;
14
-
15
- constructor(public db: Pool, public dbSpare: Pool, public dbMssql: ConnectionPool, public logger: Logger, public cache: Memcached) {
16
- if(db && dbSpare) {
17
- const dbQuery = db.query.bind(db);
18
- db.query = (function(text: any, values: any, cb: any) {
19
- if((this.idleCount + this.waitingCount) >= this.totalCount && this.totalCount === this.options.max)
20
- return dbSpare.query(text, values, cb);
21
- return dbQuery(text, values, cb);
22
- }).bind(db);
23
- }
24
- this.Migration = new MigrationRepository(db, dbMssql, logger);
25
- this.ApiCall = new ApiCallRepository(db, dbMssql, logger);
26
- }
27
-
28
- // TODO: alter table migration if exists without ok column
29
- migrate(migrationsPath: string, callback: (() => void), onlyAboveOrEquals = 0) {
30
- (this.db ? Promise.all([
31
- this.db.query(`CREATE TABLE IF NOT EXISTS migration (
32
- id integer PRIMARY KEY,
33
- hash text NOT NULL,
34
- "sqlUp" text NOT NULL,
35
- "sqlDown" text NOT NULL,
36
- state integer NOT NULL,
37
- skip boolean NOT NULL
38
- )`),
39
- this.db.query(`ALTER TABLE migration ADD COLUMN IF NOT EXISTS skip BOOLEAN NOT NULL DEFAULT FALSE`)]) : Promise.all([
40
- this.dbMssql.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name=\'migration\' AND xtype=\'U\') CREATE TABLE migration (
41
- id int PRIMARY KEY,
42
- hash text NOT NULL,
43
- "sqlUp" text NOT NULL,
44
- "sqlDown" text NOT NULL,
45
- state int NOT NULL,
46
- skip bit NOT NULL
47
- )`),
48
- this.dbMssql.query(`IF NOT EXISTS (
49
- SELECT *
50
- FROM INFORMATION_SCHEMA.COLUMNS
51
- WHERE TABLE_NAME = 'migration'
52
- AND COLUMN_NAME = 'skip'
53
- )
54
- BEGIN
55
- ALTER TABLE migration ADD skip BIT NOT NULL DEFAULT 0;
56
- END`)])).then(() => {
57
- this.Migration.getAllBy('id').then((migrations: Migration[]) => {
58
- if(migrations.find(migration => migration.state !== 0)) process.exit(4); // Have to fix manually
59
- // Read the new ones
60
- fs.readdir(migrationsPath, (_, files) => {
61
- const migrationsAvailable = files
62
- .filter(file => /[0-9]+\.sql/.test(file))
63
- .map(file => parseInt(file.split('.sql')[0], 10))
64
- .filter(file => file > 0)
65
- .sort((a, b) => a - b)
66
- .map(file => {
67
- const content = fs.readFileSync(migrationsPath + file + '.sql', 'utf-8');
68
- return {
69
- id: file,
70
- content: content,
71
- hash: crypto.createHash('sha256').update(content).digest('hex')
72
- };
73
- });
74
- if(migrationsAvailable.length === 0
75
- || migrationsAvailable.length
76
- !== migrationsAvailable[migrationsAvailable.length - 1].id) process.exit(5); // Did not use OK files
77
- let highestCommon = onlyAboveOrEquals;
78
- while(highestCommon < migrations.length && highestCommon < migrationsAvailable.length
79
- && migrations[highestCommon].hash === migrationsAvailable[highestCommon].hash)
80
- highestCommon++;
81
- this.applyDownUntil(migrations, migrations.length, highestCommon).then(highestCommon => {
82
- this.applyUpUntil(migrationsAvailable, Math.min(highestCommon, migrations.length), migrationsAvailable.length).then(callback, process.exit);
83
- }, process.exit);
84
- });
85
- }, () => process.exit(3));
86
- }, () => process.exit(2));
87
- }
88
-
89
- lockTables(tables: ModelRepr[], client: ClientBase | Transaction): Promise<any> {
90
- if(this.db)
91
- return Promise.all(tables.map(t => (<ClientBase>client).query('LOCK TABLE ' + t.table + ' IN EXCLUSIVE MODE')));
92
- return Promise.all(tables.map(t => (<Transaction>client).request().query('SELECT id FROM ' + t.table + ' WITH (UPDLOCK)')));
93
- }
94
-
95
- private applyUpUntil(migrations: {id: number, content: string, hash: string}[], current: number, until: number): Promise<void> {
96
- if(current < until)
97
- return this.applyUp(migrations[current]).then(() => this.applyUpUntil(migrations, current + 1, until));
98
- return Promise.resolve();
99
- }
100
-
101
- private applyUp(migration: {id: number, content: string, hash: string}): Promise<void> {
102
- return new Promise((resolve, reject) => {
103
- const sqlParts = migration.content.split(/-{4,}/);
104
- this.Migration.create({
105
- id: migration.id,
106
- hash: migration.hash,
107
- sqlUp: sqlParts[0],
108
- sqlDown: sqlParts[1],
109
- state: 2,
110
- skip: false
111
- }).then(() => {
112
- (<any>(this.db|| this.dbMssql)).query(sqlParts[0], (err: any) => {
113
- if(err) {
114
- console.error(err);
115
- reject(10);
116
- } else {
117
- (<any>(this.db|| this.dbMssql)).query('UPDATE "migration" SET "state"=0 WHERE "id"=' + migration.id, (err2: any) => {
118
- if(err2) reject(11); // No cleanup
119
- else resolve();
120
- });
121
- }
122
- });
123
- }, () => process.exit(9));
124
- });
125
- }
126
-
127
- private applyDownUntil(migrations: Migration[], current: number, until: number): Promise<number> {
128
- if(current > until && !migrations[current - 1]?.skip) {
129
- current--;
130
- return this.applyDown(migrations[current]).then(() => this.applyDownUntil(migrations, current, until));
131
- }
132
- return Promise.resolve(current);
133
- }
134
-
135
- private applyDown(migration: Migration): Promise<void> {
136
- return new Promise((resolve, reject) => {
137
- (<any>(this.db|| this.dbMssql)).query('UPDATE "migration" SET "state"=1 WHERE "id"=' + migration.id, (err: any) => {
138
- if(err) reject(6); // No required change
139
- else (<any>(this.db|| this.dbMssql)).query(migration.sqlDown, (err2: any) => {
140
- if(err2) {
141
- console.error(err2);
142
- reject(7);
143
- } // No apply down
144
- else (<any>(this.db|| this.dbMssql)).query('DELETE FROM "migration" WHERE "id"=' + migration.id, (err3: any) => {
145
- if(err3 && migration.id !== 1) reject(8); // No cleanup for not base migration
146
- else {
147
- if(migration.id === 1) {
148
- (this.db ? this.db.query('CREATE TABLE IF NOT EXISTS migration (' +
149
- 'id integer PRIMARY KEY,' +
150
- 'hash text NOT NULL,' +
151
- '"sqlUp" text NOT NULL,' +
152
- '"sqlDown" text NOT NULL,' +
153
- 'state integer NOT NULL' +
154
- ')') : this.dbMssql.query('if not exists (select * from sysobjects where name=\'migration\' and xtype=\'U\') CREATE TABLE migration (' +
155
- 'id int PRIMARY KEY,' +
156
- 'hash text NOT NULL,' +
157
- '"sqlUp" text NOT NULL,' +
158
- '"sqlDown" text NOT NULL,' +
159
- 'state int NOT NULL' +
160
- ')')).then(() => resolve(), reject);
161
- } else resolve();
162
- }
163
- });
164
- });
165
- });
166
- });
167
- }
168
- }
1
+ import * as crypto from 'crypto';
2
+ import * as fs from 'fs';
3
+ import * as Memcached from 'memcached';
4
+ import {ConnectionPool, Transaction} from 'mssql';
5
+ import {ClientBase, Pool} from 'pg';
6
+ import {Logger} from 'winston';
7
+ import { ApiCallRepository } from '../ApiCall';
8
+ import { Migration, MigrationRepository } from '../Migration';
9
+ import {ModelRepr} from './ModelDao';
10
+
11
+ export class BaseModelRepository {
12
+ Migration: MigrationRepository;
13
+ ApiCall: ApiCallRepository;
14
+
15
+ constructor(public db: Pool, public dbSpare: Pool, public dbMssql: ConnectionPool, public logger: Logger, public cache: Memcached) {
16
+ if(db && dbSpare) {
17
+ const dbQuery = db.query.bind(db);
18
+ db.query = (function(text: any, values: any, cb: any) {
19
+ if((this.idleCount + this.waitingCount) >= this.totalCount && this.totalCount === this.options.max)
20
+ return dbSpare.query(text, values, cb);
21
+ return dbQuery(text, values, cb);
22
+ }).bind(db);
23
+ }
24
+ this.Migration = new MigrationRepository(db, dbMssql, logger);
25
+ this.ApiCall = new ApiCallRepository(db, dbMssql, logger);
26
+ }
27
+
28
+ // TODO: alter table migration if exists without ok column
29
+ migrate(migrationsPath: string, callback: (() => void), onlyAboveOrEquals?: number, onlyBelow?: number) {
30
+ (this.db ? Promise.all([
31
+ this.db.query(`CREATE TABLE IF NOT EXISTS migration (
32
+ id integer PRIMARY KEY,
33
+ hash text NOT NULL,
34
+ "sqlUp" text NOT NULL,
35
+ "sqlDown" text NOT NULL,
36
+ state integer NOT NULL,
37
+ skip boolean NOT NULL
38
+ )`),
39
+ this.db.query(`ALTER TABLE migration ADD COLUMN IF NOT EXISTS skip BOOLEAN NOT NULL DEFAULT FALSE`)]) : Promise.all([
40
+ this.dbMssql.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name=\'migration\' AND xtype=\'U\') CREATE TABLE migration (
41
+ id int PRIMARY KEY,
42
+ hash text NOT NULL,
43
+ "sqlUp" text NOT NULL,
44
+ "sqlDown" text NOT NULL,
45
+ state int NOT NULL,
46
+ skip bit NOT NULL
47
+ )`),
48
+ this.dbMssql.query(`IF NOT EXISTS (
49
+ SELECT *
50
+ FROM INFORMATION_SCHEMA.COLUMNS
51
+ WHERE TABLE_NAME = 'migration'
52
+ AND COLUMN_NAME = 'skip'
53
+ )
54
+ BEGIN
55
+ ALTER TABLE migration ADD skip BIT NOT NULL DEFAULT 0;
56
+ END`)])).then(() => {
57
+ this.Migration.getAllBy('id').then((migrations: Migration[]) => {
58
+ if(migrations.find(migration => migration.state !== 0)) process.exit(4); // Have to fix manually
59
+ // Read the new ones
60
+ fs.readdir(migrationsPath, (_, files) => {
61
+ const migrationsAvailable = files
62
+ .filter(file => /[0-9]+\.sql/.test(file))
63
+ .map(file => parseInt(file.split('.sql')[0], 10))
64
+ .filter(file => file > 0)
65
+ .sort((a, b) => a - b)
66
+ .map(file => {
67
+ const content = fs.readFileSync(migrationsPath + file + '.sql', 'utf-8');
68
+ return {
69
+ id: file,
70
+ content: content,
71
+ hash: crypto.createHash('sha256').update(content).digest('hex')
72
+ };
73
+ });
74
+ const minAvailableId = migrationsAvailable.length > 0 ? migrationsAvailable[0].id : 0;
75
+ const maxAvailableId = migrationsAvailable.length > 0 ? migrationsAvailable[migrationsAvailable.length - 1].id : Infinity;
76
+ migrations = migrations.filter(m => m.id >= minAvailableId && m.id <= maxAvailableId);
77
+ if(onlyAboveOrEquals) migrations = migrations.filter(m => m.id >= onlyAboveOrEquals);
78
+ if(onlyBelow) migrations = migrations.filter(m => m.id < onlyBelow);
79
+ if(migrationsAvailable.length === 0 && migrations.length === 0) process.exit(5);
80
+ if(migrationsAvailable.length && migrationsAvailable.length !== (migrationsAvailable[migrationsAvailable.length - 1].id - migrationsAvailable[0].id + 1)) process.exit(5);
81
+ let highestCommon = 0;
82
+ while(highestCommon < migrations.length
83
+ && highestCommon < migrationsAvailable.length
84
+ && migrations[highestCommon]
85
+ && migrationsAvailable[highestCommon]
86
+ && migrations[highestCommon].hash === migrationsAvailable[highestCommon].hash)
87
+ highestCommon++;
88
+ this.applyDownUntil(migrations, migrations.length, highestCommon).then(appliedId => {
89
+ this.applyUpUntil(migrationsAvailable, Math.min(appliedId, migrations.length), migrationsAvailable.length).then(callback, process.exit);
90
+ }, process.exit);
91
+ });
92
+ }, () => process.exit(3));
93
+ }, () => process.exit(2));
94
+ }
95
+
96
+ lockTables(tables: ModelRepr[], client: ClientBase | Transaction): Promise<any> {
97
+ if(this.db)
98
+ return Promise.all(tables.map(t => (<ClientBase>client).query('LOCK TABLE ' + t.table + ' IN EXCLUSIVE MODE')));
99
+ return Promise.all(tables.map(t => (<Transaction>client).request().query('SELECT id FROM ' + t.table + ' WITH (UPDLOCK)')));
100
+ }
101
+
102
+ private applyUpUntil(migrations: {id: number, content: string, hash: string}[], current: number, until: number): Promise<void> {
103
+ if(current < until) {
104
+ console.log('Applying migration ' + migrations[current].id);
105
+ return this.applyUp(migrations[current]).then(() => this.applyUpUntil(migrations, current + 1, until));
106
+ }
107
+ return Promise.resolve();
108
+ }
109
+
110
+ private applyUp(migration: {id: number, content: string, hash: string}): Promise<void> {
111
+ return new Promise((resolve, reject) => {
112
+ const sqlParts = migration.content.split(/-{4,}/);
113
+ this.Migration.create({
114
+ id: migration.id,
115
+ hash: migration.hash,
116
+ sqlUp: sqlParts[0],
117
+ sqlDown: sqlParts[1],
118
+ state: 2,
119
+ skip: false
120
+ }).then(() => {
121
+ (<any>(this.db|| this.dbMssql)).query(sqlParts[0], (err: any) => {
122
+ if(err) {
123
+ console.error(err);
124
+ reject(10);
125
+ } else {
126
+ (<any>(this.db|| this.dbMssql)).query('UPDATE "migration" SET "state"=0 WHERE "id"=' + migration.id, (err2: any) => {
127
+ if(err2) reject(11); // No cleanup
128
+ else resolve();
129
+ });
130
+ }
131
+ });
132
+ }, () => process.exit(9));
133
+ });
134
+ }
135
+
136
+ private applyDownUntil(migrations: Migration[], current: number, until: number): Promise<number> {
137
+ if(current > until && !migrations[current - 1]?.skip) {
138
+ current--;
139
+ console.log('Reverting migration ' + migrations[current].id);
140
+ return this.applyDown(migrations[current]).then(() => this.applyDownUntil(migrations, current, until));
141
+ }
142
+ return Promise.resolve(current);
143
+ }
144
+
145
+ private applyDown(migration: Migration): Promise<void> {
146
+ return new Promise((resolve, reject) => {
147
+ (<any>(this.db|| this.dbMssql)).query('UPDATE "migration" SET "state"=1 WHERE "id"=' + migration.id, (err: any) => {
148
+ if(err) reject(6); // No required change
149
+ else (<any>(this.db|| this.dbMssql)).query(migration.sqlDown, (err2: any) => {
150
+ if(err2) {
151
+ console.error(err2);
152
+ reject(7);
153
+ } // No apply down
154
+ else (<any>(this.db|| this.dbMssql)).query('DELETE FROM "migration" WHERE "id"=' + migration.id, (err3: any) => {
155
+ if(err3 && migration.id !== 1) reject(8); // No cleanup for not base migration
156
+ else {
157
+ if(migration.id === 1) {
158
+ (this.db ? this.db.query('CREATE TABLE IF NOT EXISTS migration (' +
159
+ 'id integer PRIMARY KEY,' +
160
+ 'hash text NOT NULL,' +
161
+ '"sqlUp" text NOT NULL,' +
162
+ '"sqlDown" text NOT NULL,' +
163
+ 'state integer NOT NULL' +
164
+ ')') : this.dbMssql.query('if not exists (select * from sysobjects where name=\'migration\' and xtype=\'U\') CREATE TABLE migration (' +
165
+ 'id int PRIMARY KEY,' +
166
+ 'hash text NOT NULL,' +
167
+ '"sqlUp" text NOT NULL,' +
168
+ '"sqlDown" text NOT NULL,' +
169
+ 'state int NOT NULL' +
170
+ ')')).then(() => resolve(), reject);
171
+ } else resolve();
172
+ }
173
+ });
174
+ });
175
+ });
176
+ });
177
+ }
178
+ }
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CryptModelDao = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const util_1 = require("util");
6
+ const ModelDao_1 = require("./ModelDao");
7
+ const randomFillAsync = (0, util_1.promisify)(crypto_1.randomFill);
8
+ class CryptModelDao extends ModelDao_1.ModelDao {
9
+ constructor(keyBase64, encryptedColumns, ...args) {
10
+ super(...args);
11
+ this.key = Buffer.from(keyBase64, 'base64');
12
+ this.encryptedColumns = encryptedColumns;
13
+ }
14
+ serializeWrapper(instance, request) {
15
+ const props = this.serialize(instance, request);
16
+ const encryptPromises = [];
17
+ this.encryptedColumns.forEach(col => {
18
+ const idx = this.updateDefinition.split(',').findIndex(def => def.trim().startsWith('"' + col + '"') || def.trim().startsWith(col + '='));
19
+ if (idx >= 0) {
20
+ const val = request ? request.parameters[idx] : props[idx];
21
+ if (val !== null && val !== undefined) {
22
+ const encryptPromise = this.encrypt(String(val)).then(encrypted => {
23
+ if (request)
24
+ request.replaceInput(String(idx + 1), encrypted);
25
+ else
26
+ props[idx] = encrypted;
27
+ });
28
+ encryptPromises.push(encryptPromise);
29
+ }
30
+ }
31
+ });
32
+ if (encryptPromises.length > 0) {
33
+ return Promise.all(encryptPromises).then(() => props);
34
+ }
35
+ return props;
36
+ }
37
+ buildObjectWrapper(row) {
38
+ const decryptPromises = [];
39
+ this.encryptedColumns.forEach(col => {
40
+ if (row[col] !== null && row[col] !== undefined) {
41
+ const decryptPromise = this.decrypt(String(row[col])).then(decrypted => {
42
+ row[col] = decrypted;
43
+ });
44
+ decryptPromises.push(decryptPromise);
45
+ }
46
+ });
47
+ if (decryptPromises.length > 0) {
48
+ return Promise.all(decryptPromises).then(() => this.buildObject(row));
49
+ }
50
+ return this.buildObject(row);
51
+ }
52
+ async encrypt(decrypted) {
53
+ const iv = new Uint8Array(16);
54
+ await randomFillAsync(iv);
55
+ const cipher = (0, crypto_1.createCipheriv)(CryptModelDao.ALGORITHM, this.key, iv);
56
+ let encrypted = '';
57
+ cipher.setEncoding('base64');
58
+ cipher.on('data', (chunk) => encrypted += chunk);
59
+ cipher.write(decrypted);
60
+ cipher.end();
61
+ return `$$enc$$:${Buffer.from(iv).toString('base64')}${encrypted}`;
62
+ }
63
+ async decrypt(encrypted) {
64
+ if (!encrypted.startsWith('$$enc$$:')) {
65
+ return encrypted;
66
+ }
67
+ encrypted = encrypted.slice(8);
68
+ const iv = new Uint8Array(Buffer.from(encrypted.slice(0, 24), 'base64'));
69
+ const decipher = (0, crypto_1.createDecipheriv)(CryptModelDao.ALGORITHM, this.key, iv);
70
+ let decrypted = '';
71
+ decipher.on('readable', () => {
72
+ for (let chunk = decipher.read(); chunk !== null; chunk = decipher.read()) {
73
+ decrypted += chunk.toString('base64');
74
+ }
75
+ });
76
+ decipher.write(encrypted.slice(24), 'base64');
77
+ decipher.end();
78
+ return Buffer.from(decrypted, 'base64').toString('utf8');
79
+ }
80
+ }
81
+ exports.CryptModelDao = CryptModelDao;
82
+ CryptModelDao.ALGORITHM = 'aes-256-cbc';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "anote-server-libs",
3
- "version": "0.9.5",
3
+ "version": "0.9.7",
4
4
  "description": "Helpers for express-TS servers",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1",