@galadrim/galadmin 0.1.236 → 0.2.6

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 (64) hide show
  1. package/.github/workflows/main.yml +33 -2
  2. package/README.md +65 -0
  3. package/dist/api.d.ts +16 -0
  4. package/dist/api.js +240 -189
  5. package/dist/api.js.map +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/index.js.map +1 -1
  8. package/dist/tsconfig.tsbuildinfo +1 -1
  9. package/dist/utils/dbManager.d.ts +5 -0
  10. package/dist/utils/dbManager.js +146 -11
  11. package/dist/utils/dbManager.js.map +1 -1
  12. package/dist/utils/imageDimensions.d.ts +5 -0
  13. package/dist/utils/imageDimensions.js +98 -0
  14. package/dist/utils/imageDimensions.js.map +1 -0
  15. package/jest.config.js +43 -0
  16. package/jest.integration.config.js +16 -0
  17. package/package.json +30 -10
  18. package/src/api.ts +284 -217
  19. package/src/front/src/App.test.js +28 -0
  20. package/src/front/src/components/OutsideClickHandler.test.js +53 -0
  21. package/src/front/src/components/RedirectToFirstView.test.js +38 -0
  22. package/src/front/src/utils/checkRequiredColumns.test.js +46 -0
  23. package/src/front/src/utils/evalExpression.test.js +29 -0
  24. package/src/index.ts +1 -1
  25. package/src/utils/dbManager.ts +243 -102
  26. package/src/utils/imageDimensions.ts +112 -0
  27. package/tests/__mocks__/@aws-sdk/client-s3.js +6 -0
  28. package/tests/__mocks__/@aws-sdk/s3-request-presigner.js +3 -0
  29. package/tests/__mocks__/@google-cloud/storage.js +7 -0
  30. package/tests/__mocks__/argon2.js +3 -0
  31. package/tests/__mocks__/axios.js +7 -0
  32. package/tests/__mocks__/connect-pg-simple.js +24 -0
  33. package/tests/__mocks__/express-mysql-session.js +24 -0
  34. package/tests/__mocks__/mysql2/promise.js +3 -0
  35. package/tests/__mocks__/pg.js +3 -0
  36. package/tests/__mocks__/rollup.js +5 -0
  37. package/tests/__mocks__/ssh2-sftp-client.js +10 -0
  38. package/tests/api-helpers.test.ts +376 -0
  39. package/tests/dbManager.init.test.ts +129 -0
  40. package/tests/dbManager.test.ts +265 -0
  41. package/tests/edge-cases.test.ts +167 -0
  42. package/tests/helpers/app.ts +69 -0
  43. package/tests/helpers/fakeDb.ts +66 -0
  44. package/tests/helpers/fakePool.ts +76 -0
  45. package/tests/helpers/fixtures.ts +68 -0
  46. package/tests/imageDimensions.test.ts +111 -0
  47. package/tests/index.sessionStore.test.ts +19 -0
  48. package/tests/index.test.ts +363 -0
  49. package/tests/integration/__mocks__/axios.js +3 -0
  50. package/tests/integration/dbHarness.ts +381 -0
  51. package/tests/integration/dbManager.integration.test.ts +69 -0
  52. package/tests/integration/globalSetup.ts +43 -0
  53. package/tests/integration/globalTeardown.ts +42 -0
  54. package/tests/integration/routes.authorization.integration.test.ts +319 -0
  55. package/tests/integration/routes.config.integration.test.ts +189 -0
  56. package/tests/integration/routes.crud.integration.test.ts +805 -0
  57. package/tests/integration/routes.custom.integration.test.ts +376 -0
  58. package/tests/integration/routes.foreign.integration.test.ts +306 -0
  59. package/tests/integration/routes.importExport.integration.test.ts +404 -0
  60. package/tests/integration/routes.integration.test.ts +366 -0
  61. package/tests/integration/routes.postgresql.integration.test.ts +88 -0
  62. package/tests/integration/routes.records.integration.test.ts +634 -0
  63. package/tests/integration/routes.upload.integration.test.ts +425 -0
  64. package/tests/setup/silence-console.ts +15 -0
@@ -0,0 +1,53 @@
1
+ import { render, fireEvent } from "@testing-library/react";
2
+ import OutsideClickHandler from "./OutsideClickHandler";
3
+
4
+ describe("OutsideClickHandler", () => {
5
+ it("renders its children", () => {
6
+ const { getByText } = render(
7
+ <OutsideClickHandler onOutsideClick={() => {}}>
8
+ <span>inner content</span>
9
+ </OutsideClickHandler>,
10
+ );
11
+ expect(getByText("inner content")).toBeTruthy();
12
+ });
13
+
14
+ it("does not fire when clicking inside", () => {
15
+ const onOutsideClick = jest.fn();
16
+ const { getByText } = render(
17
+ <OutsideClickHandler onOutsideClick={onOutsideClick}>
18
+ <span>inner</span>
19
+ </OutsideClickHandler>,
20
+ );
21
+ fireEvent.mouseDown(getByText("inner"));
22
+ expect(onOutsideClick).not.toHaveBeenCalled();
23
+ });
24
+
25
+ it("fires on a mousedown outside of the wrapper", () => {
26
+ const onOutsideClick = jest.fn();
27
+ const { getByText } = render(
28
+ <div>
29
+ <div data-testid="outside">outside</div>
30
+ <OutsideClickHandler onOutsideClick={onOutsideClick}>
31
+ <span>inner</span>
32
+ </OutsideClickHandler>
33
+ </div>,
34
+ );
35
+ fireEvent.mouseDown(getByText("outside"));
36
+ expect(onOutsideClick).toHaveBeenCalledTimes(1);
37
+ });
38
+
39
+ it("stops listening after unmount", () => {
40
+ const onOutsideClick = jest.fn();
41
+ const { unmount, getByText } = render(
42
+ <div>
43
+ <div>outside</div>
44
+ <OutsideClickHandler onOutsideClick={onOutsideClick}>
45
+ <span>inner</span>
46
+ </OutsideClickHandler>
47
+ </div>,
48
+ );
49
+ unmount();
50
+ fireEvent.mouseDown(document.body);
51
+ expect(onOutsideClick).not.toHaveBeenCalled();
52
+ });
53
+ });
@@ -0,0 +1,38 @@
1
+ import { render } from "@testing-library/react";
2
+ import { MemoryRouter, Route, Switch } from "react-router-dom";
3
+ import RedirectToFirstView from "./RedirectToFirstView";
4
+ import { ConfigContext } from "../contexts/ConfigContext";
5
+
6
+ function renderWithViews(views) {
7
+ return render(
8
+ <ConfigContext.Provider value={{ views }}>
9
+ <MemoryRouter initialEntries={["/"]}>
10
+ <Switch>
11
+ <Route exact path="/" component={RedirectToFirstView} />
12
+ <Route path="/records/0" render={() => <div>LANDING-records</div>} />
13
+ <Route path="/iframe/0" render={() => <div>LANDING-iframe</div>} />
14
+ <Route
15
+ path="/customView/0"
16
+ render={() => <div>LANDING-customView</div>}
17
+ />
18
+ </Switch>
19
+ </MemoryRouter>
20
+ </ConfigContext.Provider>,
21
+ );
22
+ }
23
+
24
+ describe("RedirectToFirstView", () => {
25
+ it.each([
26
+ ["table", "LANDING-records"],
27
+ ["iframe", "LANDING-iframe"],
28
+ ["custom", "LANDING-customView"],
29
+ ])("redirects a %s first view to its route", (type, landing) => {
30
+ const { getByText } = renderWithViews([{ type, label: "First" }]);
31
+ expect(getByText(landing)).toBeTruthy();
32
+ });
33
+
34
+ it("renders nothing when the config has no views", () => {
35
+ const { container } = renderWithViews([]);
36
+ expect(container.innerHTML).toBe("");
37
+ });
38
+ });
@@ -0,0 +1,46 @@
1
+ import checkRequiredColumns from "./checkRequiredColumns";
2
+
3
+ describe("checkRequiredColumns", () => {
4
+ beforeEach(() => {
5
+ global.window.swal = jest.fn();
6
+ });
7
+
8
+ const columns = [
9
+ { label: "Nom", name: "fruitName", required: true },
10
+ { label: "Note", name: "note", required: true },
11
+ { label: "Acidité", name: "acidity" },
12
+ ];
13
+
14
+ it("accepts data where every required column is filled", () => {
15
+ expect(
16
+ checkRequiredColumns(columns, { fruitName: "pomme", note: "ok" }),
17
+ ).toBe(true);
18
+ expect(global.window.swal).not.toHaveBeenCalled();
19
+ });
20
+
21
+ it("rejects data missing a required column and shows a message", () => {
22
+ expect(checkRequiredColumns(columns, { fruitName: "pomme", note: "" })).toBe(
23
+ false,
24
+ );
25
+ expect(global.window.swal).toHaveBeenCalledWith(
26
+ expect.objectContaining({
27
+ text: "Le champ requis Note n'a pas été rempli",
28
+ }),
29
+ );
30
+ });
31
+
32
+ it("uses the plural message when several required columns are missing", () => {
33
+ expect(checkRequiredColumns(columns, {})).toBe(false);
34
+ expect(global.window.swal).toHaveBeenCalledWith(
35
+ expect.objectContaining({
36
+ text: "Les champs requis Nom, Note n'ont pas été remplis",
37
+ }),
38
+ );
39
+ });
40
+
41
+ it("treats null as unfilled and optional columns as ignorable", () => {
42
+ expect(
43
+ checkRequiredColumns(columns, { fruitName: "pomme", note: "n", acidity: null }),
44
+ ).toBe(true);
45
+ });
46
+ });
@@ -0,0 +1,29 @@
1
+ import evalExpression from "./evalExpression";
2
+
3
+ describe("evalExpression", () => {
4
+ it("evaluates an arithmetic expression over the data", () => {
5
+ expect(evalExpression("a + b", { a: 1, b: 2 })).toBe(3);
6
+ });
7
+
8
+ it("interpolates string values", () => {
9
+ expect(
10
+ evalExpression("fruitName + ' !'", { fruitName: "pomme" }),
11
+ ).toBe("pomme !");
12
+ });
13
+
14
+ it("escapes single quotes in string data", () => {
15
+ expect(
16
+ evalExpression("name.toUpperCase()", { name: "l'orange" }),
17
+ ).toBe("L'ORANGE");
18
+ });
19
+
20
+ it("serializes object values", () => {
21
+ expect(evalExpression("obj.x", { obj: { x: 42 } })).toBe(42);
22
+ });
23
+
24
+ it("returns 'Error' for a broken expression instead of throwing", () => {
25
+ const consoleError = jest.spyOn(console, "error").mockImplementation();
26
+ expect(evalExpression("a +++", { a: 1 })).toBe("Error");
27
+ consoleError.mockRestore();
28
+ });
29
+ });
package/src/index.ts CHANGED
@@ -51,7 +51,7 @@ export default (config: Config): any => {
51
51
  }),
52
52
  createTableIfMissing: true,
53
53
  tableName: 'galadmin_sessions'
54
- }) : new SessionStore({
54
+ }) : new (SessionStore(session))({
55
55
  schema: { tableName: 'galadmin_sessions' }
56
56
  }, mysql2.createPool({
57
57
  host: config.mysql.host,
@@ -1,132 +1,273 @@
1
1
  import * as mysql from "mysql";
2
2
  import * as mysql2 from "mysql2";
3
- import * as pg from 'pg';
3
+ import * as pg from "pg";
4
4
 
5
5
  export function quoteIdentifier(name: string, dbType: string): string {
6
- const quoteChar = dbType === "POSTGRESQL" ? '"' : '`';
6
+ const quoteChar = dbType === "POSTGRESQL" ? '"' : "`";
7
7
  return quoteChar + name + quoteChar;
8
8
  }
9
9
 
10
- function convertQuery(mysqlQuery, params) {
11
- let pgQuery = '';
12
- let pgParams = [];
13
-
14
- let paramIndex = 1;
15
- let charIndex = 0;
16
-
17
- while (charIndex < mysqlQuery.length) {
18
- if (mysqlQuery.charAt(charIndex) === '?' && mysqlQuery.charAt(charIndex + 1) === '?') {
19
- // Replace "??"
20
- pgQuery += params.shift();
21
- charIndex += 2; // Skip two characters
22
- } else if (mysqlQuery.charAt(charIndex) === '?') {
23
- // Replace "?"
24
- pgQuery += `$${paramIndex++}`;
25
- pgParams.push(params.shift());
26
- charIndex++; // Skip one character
10
+ function endOfLiteralOrComment(query: string, start: number): number {
11
+ const ch = query.charAt(start);
12
+ const next = query.charAt(start + 1);
13
+
14
+ if (ch === '-' && next === '-') {
15
+ const newline = query.indexOf('\n', start);
16
+ return newline === -1 ? query.length : newline;
17
+ }
18
+ if (ch === '/' && next === '*') {
19
+ const close = query.indexOf('*/', start + 2);
20
+ return close === -1 ? query.length : close + 2;
21
+ }
22
+ if (ch !== "'") {
23
+ return -1;
24
+ }
25
+
26
+ const prefix = query.charAt(start - 1);
27
+ const backslashEscapes = (prefix === 'E' || prefix === 'e') && !/[\w$]/.test(query.charAt(start - 2));
28
+
29
+ let index = start + 1;
30
+ while (index < query.length) {
31
+ const current = query.charAt(index);
32
+ if (backslashEscapes && current === '\\') {
33
+ index += 2;
34
+ } else if (current === "'" && query.charAt(index + 1) === "'") {
35
+ index += 2;
36
+ } else if (current === "'") {
37
+ return index + 1;
27
38
  } else {
28
- pgQuery += mysqlQuery.charAt(charIndex);
29
- charIndex++; // Go to next character
39
+ index++;
30
40
  }
31
41
  }
32
-
33
- return {
34
- pgQuery,
35
- pgParams,
36
- };
42
+ return query.length;
37
43
  }
38
44
 
39
- function quotePostgresQuery(query) {
40
- query = query.replace(/`/g, '"');
45
+ export function convertQuery(mysqlQuery, params) {
46
+ let pgQuery = "";
47
+ let pgParams = [];
41
48
 
42
- const reservedWords = ["1","COUNT","*","UPDATE","SELECT","SET","=","INSERT","INTO","DELETE","FROM","WHERE","AND","OR","JOIN","ON","AS","IN","ILIKE","LIKE","EXISTS","ALL","ANY","NOT","NULL","TRUE","FALSE","GROUP","BY","ORDER","LIMIT","OFFSET","DESC","VALUES","LEFT","RIGHT","USING","CONCAT","CASE","WHEN","THEN","ELSE","END","ASC","IS","INTERVAL","CURRENT_DATE","SUM","COALESCE","-","ROUND","DATE_TRUNC","<>","+","DISTINCT","MAX","MIN","AVG","BIT_AND","BIT_OR","BOOL_AND","BOOL_OR","XMLAGG","STRING_AGG","EVERY","CORR","COVAR_POP","COVAR_SAMP","VAR_POP","VAR_SAMP","VARIANCE","REGR_SLOPE","REGR_INTERCEPT","REGR_COUNT","REGR_R2","REGR_AVGX","REGR_AVGY","REGR_SXX","REGR_SXY","REGR_SYY"];
49
+ let paramIndex = 1;
50
+ let charIndex = 0;
43
51
 
44
- const wordsToAddQuotes = new Set()
45
- const parts = query.split(/[ ,\(\)]/);
52
+ // Placeholders (`?` / `??`) only carry meaning OUTSIDE string literals:
53
+ // a literal `?` inside '…' must survive verbatim instead of being turned
54
+ // into a $N placeholder that would consume a parameter slot.
55
+ while (charIndex < mysqlQuery.length) {
56
+ const ch = mysqlQuery.charAt(charIndex);
57
+ const next = mysqlQuery.charAt(charIndex + 1);
58
+ const verbatimEnd = endOfLiteralOrComment(mysqlQuery, charIndex);
46
59
 
47
- let inString = false;
60
+ if (verbatimEnd !== -1) {
61
+ pgQuery += mysqlQuery.slice(charIndex, verbatimEnd);
62
+ charIndex = verbatimEnd;
63
+ } else if (ch === "?" && next === "?") {
64
+ // Replace "??"
65
+ pgQuery += params.shift();
66
+ charIndex += 2; // Skip two characters
67
+ } else if (ch === "?") {
68
+ // Replace "?"
69
+ pgQuery += `$${paramIndex++}`;
70
+ pgParams.push(params.shift());
71
+ charIndex++; // Skip one character
72
+ } else {
73
+ pgQuery += ch;
74
+ charIndex++; // Go to next character
75
+ }
76
+ }
48
77
 
49
- for (let i = 0; i < parts.length; i++) {
50
- const part = parts[i].trim();
51
- if (!part) {
52
- continue
53
- }
54
- if (part.split(/['"]/).length % 2 === 0) {
55
- inString = !inString;
56
- }
78
+ return {
79
+ pgQuery,
80
+ pgParams,
81
+ };
82
+ }
57
83
 
58
- if (inString || part.startsWith("$") || part.includes("'") || part.includes('"') || reservedWords.includes(part.toUpperCase())) {
84
+ export function quotePostgresQuery(query) {
85
+ query = query.replace(/`/g, '"');
59
86
 
60
- } else {
61
- for (let x of part.split(".")) {
62
- if (isNaN(x)) {
63
- wordsToAddQuotes.add(x)
64
- }
65
- }
66
- }
87
+ const reservedWords = [
88
+ "1",
89
+ "COUNT",
90
+ "*",
91
+ "UPDATE",
92
+ "SELECT",
93
+ "SET",
94
+ "=",
95
+ "INSERT",
96
+ "INTO",
97
+ "DELETE",
98
+ "FROM",
99
+ "WHERE",
100
+ "AND",
101
+ "OR",
102
+ "JOIN",
103
+ "ON",
104
+ "AS",
105
+ "IN",
106
+ "ILIKE",
107
+ "LIKE",
108
+ "EXISTS",
109
+ "ALL",
110
+ "ANY",
111
+ "NOT",
112
+ "NULL",
113
+ "TRUE",
114
+ "FALSE",
115
+ "GROUP",
116
+ "BY",
117
+ "ORDER",
118
+ "LIMIT",
119
+ "OFFSET",
120
+ "DESC",
121
+ "VALUES",
122
+ "LEFT",
123
+ "RIGHT",
124
+ "USING",
125
+ "CONCAT",
126
+ "CONCAT_WS",
127
+ "CASE",
128
+ "WHEN",
129
+ "THEN",
130
+ "ELSE",
131
+ "END",
132
+ "ASC",
133
+ "IS",
134
+ "INTERVAL",
135
+ "CURRENT_DATE",
136
+ "SUM",
137
+ "COALESCE",
138
+ "HAVING",
139
+ "WITH",
140
+ "-",
141
+ "ROUND",
142
+ "DATE_TRUNC",
143
+ "<>",
144
+ "+",
145
+ "DISTINCT",
146
+ "MAX",
147
+ "MIN",
148
+ "AVG",
149
+ "BIT_AND",
150
+ "BIT_OR",
151
+ "BOOL_AND",
152
+ "BOOL_OR",
153
+ "XMLAGG",
154
+ "STRING_AGG",
155
+ "EVERY",
156
+ "CORR",
157
+ "COVAR_POP",
158
+ "COVAR_SAMP",
159
+ "VAR_POP",
160
+ "VAR_SAMP",
161
+ "VARIANCE",
162
+ "REGR_SLOPE",
163
+ "REGR_INTERCEPT",
164
+ "REGR_COUNT",
165
+ "REGR_R2",
166
+ "REGR_AVGX",
167
+ "REGR_AVGY",
168
+ "REGR_SXX",
169
+ "REGR_SXY",
170
+ "REGR_SYY",
171
+ "CONFLICT",
172
+ "DO",
173
+ "EXCLUDED",
174
+ "RETURNING",
175
+ ];
176
+
177
+ const wordsToAddQuotes = new Set();
178
+ const parts = query.split(/[ ,\(\)]/);
179
+
180
+ let inString = false;
181
+
182
+ for (let i = 0; i < parts.length; i++) {
183
+ const part = parts[i].trim();
184
+ if (!part) {
185
+ continue;
186
+ }
187
+ if (part.split(/['"]/).length % 2 === 0) {
188
+ inString = !inString;
67
189
  }
68
190
 
69
- let newQuery = query;
70
- for (let word of wordsToAddQuotes) {
71
- if (word !== "*") {
72
- newQuery = newQuery.replace(new RegExp(`(?<!["\'])\\b${word}\\b(?!["\'])`, 'g'), `"${word}"`)
191
+ if (
192
+ inString ||
193
+ part.startsWith("$") ||
194
+ part.includes("'") ||
195
+ part.includes('"') ||
196
+ reservedWords.includes(part.toUpperCase())
197
+ ) {
198
+ } else {
199
+ for (let x of part.split(".")) {
200
+ if (isNaN(x)) {
201
+ wordsToAddQuotes.add(x);
73
202
  }
203
+ }
74
204
  }
205
+ }
75
206
 
76
- newQuery = newQuery.replace(/\) LIKE /g, ") ILIKE ");
77
- newQuery = newQuery.replace(/ LIKE /g, "::text ILIKE ");
207
+ let newQuery = query;
208
+ for (let word of wordsToAddQuotes) {
209
+ if (word !== "*") {
210
+ newQuery = newQuery.replace(
211
+ new RegExp(`(?<!["\'])\\b${word}\\b(?!["\'])`, "g"),
212
+ `"${word}"`,
213
+ );
214
+ }
215
+ }
78
216
 
79
- return newQuery;
217
+ newQuery = newQuery.replace(/\) LIKE /g, ") ILIKE ");
218
+ newQuery = newQuery.replace(/ LIKE /g, "::text ILIKE ");
219
+
220
+ return newQuery;
80
221
  }
81
222
 
82
223
  export default class dbManager {
83
- _db;
84
- dbType;
85
-
86
- init(config) {
87
- if (config.mysql) {
88
- this._db = (config.useMysql2 ? mysql2 : mysql).createPool({
89
- connectionLimit: 10,
90
- host: config.mysql.host,
91
- user: config.mysql.user,
92
- password: config.mysql.password,
93
- database: config.mysql.database,
94
- port: config.mysql.port || 3306,
95
- charset: 'UTF8MB4_GENERAL_CI',
96
- dateStrings: true,
97
- // SECURITY: multi-statement queries let any SQL-injection escalate to stacked
98
- // writes / DROP. Keep OFF by default; opt in explicitly only if a config truly
99
- // relies on `;`-separated statements (none of galadmin's internal queries do).
100
- multipleStatements: config.mysql.multipleStatements === true
101
- });
102
- this.dbType = "MYSQL";
103
- } else if (config.postgresql) {
104
- this._db = new pg.Pool({
105
- host: config.postgresql.host,
106
- user: config.postgresql.user,
107
- password: config.postgresql.password,
108
- database: config.postgresql.database,
109
- port: config.postgresql.port || 5432,
110
- ssl: config.postgresql.ssl
111
- });
112
- this.dbType = "POSTGRESQL";
113
- }
114
- }
224
+ _db;
225
+ dbType;
115
226
 
116
- async query(queryString, args = []): Promise<any> {
117
- return new Promise((resolve, reject) => {
118
- if (this.dbType === "POSTGRESQL") {
119
- const result = convertQuery(queryString, args);
120
- queryString = quotePostgresQuery(result.pgQuery);
121
- args = result.pgParams;
122
- }
123
- this._db.query(queryString, args, (a, b, c) => {
124
- if (this.dbType === "MYSQL") {
125
- resolve({ err: a, rows: b, fields: c })
126
- } else if (this.dbType === "POSTGRESQL") {
127
- resolve({ err: a, rows: b?.rows, fields: b?.fields })
128
- }
129
- });
130
- });
227
+ init(config) {
228
+ if (config.mysql) {
229
+ this._db = (config.useMysql2 ? mysql2 : mysql).createPool({
230
+ connectionLimit: 10,
231
+ host: config.mysql.host,
232
+ user: config.mysql.user,
233
+ password: config.mysql.password,
234
+ database: config.mysql.database,
235
+ port: config.mysql.port || 3306,
236
+ charset: "UTF8MB4_GENERAL_CI",
237
+ dateStrings: true,
238
+ // SECURITY: multi-statement queries let any SQL-injection escalate to stacked
239
+ // writes / DROP. Keep OFF by default; opt in explicitly only if a config truly
240
+ // relies on `;`-separated statements (none of galadmin's internal queries do).
241
+ multipleStatements: config.mysql.multipleStatements === true,
242
+ });
243
+ this.dbType = "MYSQL";
244
+ } else if (config.postgresql) {
245
+ this._db = new pg.Pool({
246
+ host: config.postgresql.host,
247
+ user: config.postgresql.user,
248
+ password: config.postgresql.password,
249
+ database: config.postgresql.database,
250
+ port: config.postgresql.port || 5432,
251
+ ssl: config.postgresql.ssl,
252
+ });
253
+ this.dbType = "POSTGRESQL";
131
254
  }
255
+ }
256
+
257
+ async query(queryString, args = []): Promise<any> {
258
+ return new Promise((resolve, reject) => {
259
+ if (this.dbType === "POSTGRESQL") {
260
+ const result = convertQuery(queryString, args);
261
+ queryString = quotePostgresQuery(result.pgQuery);
262
+ args = result.pgParams;
263
+ }
264
+ this._db.query(queryString, args, (a, b, c) => {
265
+ if (this.dbType === "MYSQL") {
266
+ resolve({ err: a, rows: b, fields: c });
267
+ } else if (this.dbType === "POSTGRESQL") {
268
+ resolve({ err: a, rows: b?.rows, fields: b?.fields });
269
+ }
270
+ });
271
+ });
272
+ }
132
273
  }
@@ -0,0 +1,112 @@
1
+ import { promises as fsPromises } from "fs";
2
+
3
+ const PNG_SIGNATURE = Buffer.from([
4
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
5
+ ]);
6
+
7
+ // Enough to hold a PNG IHDR, a GIF logical screen descriptor or the JPEG
8
+ // segments (APPn/EXIF can be large) preceding the SOFn frame header.
9
+ const HEADER_LIMIT = 2 * 1024 * 1024;
10
+
11
+ export type ImageDimensions = { width: number; height: number };
12
+
13
+ async function readHeader(filePath: string): Promise<Buffer> {
14
+ const handle = await fsPromises.open(filePath, "r");
15
+ try {
16
+ const length = Math.min(HEADER_LIMIT, (await handle.stat()).size);
17
+ const buffer = Buffer.alloc(length);
18
+ await handle.read(buffer, 0, length, 0);
19
+ return buffer;
20
+ } finally {
21
+ await handle.close();
22
+ }
23
+ }
24
+
25
+ function parsePngDimensions(header: Buffer): ImageDimensions | null {
26
+ if (header.length < 24 || header.toString("latin1", 12, 16) !== "IHDR") {
27
+ return null;
28
+ }
29
+ const width = header.readUInt32BE(16);
30
+ const height = header.readUInt32BE(20);
31
+ return width > 0 && height > 0 ? { width, height } : null;
32
+ }
33
+
34
+ function parseGifDimensions(header: Buffer): ImageDimensions | null {
35
+ const signature = header.toString("latin1", 0, 6);
36
+ if (signature !== "GIF87a" && signature !== "GIF89a") {
37
+ return null;
38
+ }
39
+ const width = header.readUInt16LE(6);
40
+ const height = header.readUInt16LE(8);
41
+ return width > 0 && height > 0 ? { width, height } : null;
42
+ }
43
+
44
+ function parseJpegDimensions(header: Buffer): ImageDimensions | null {
45
+ let offset = 2;
46
+ while (offset + 4 <= header.length) {
47
+ if (header[offset] !== 0xff) {
48
+ return null;
49
+ }
50
+ const marker = header[offset + 1];
51
+ // Standalone markers (SOI, TEM, RST, EOI) carry no length field
52
+ if (
53
+ marker === 0x01 ||
54
+ marker === 0xd8 ||
55
+ marker === 0xd9 ||
56
+ (marker >= 0xd0 && marker <= 0xd7)
57
+ ) {
58
+ offset += 2;
59
+ continue;
60
+ }
61
+ // Start of scan: frame header must have appeared before this point
62
+ if (marker === 0xda || marker === 0xd9) {
63
+ return null;
64
+ }
65
+ const segmentLength = header.readUInt16BE(offset + 2);
66
+ if (segmentLength < 2) {
67
+ return null;
68
+ }
69
+ const isFrameHeader =
70
+ marker >= 0xc0 &&
71
+ marker <= 0xcf &&
72
+ marker !== 0xc4 && // DHT
73
+ marker !== 0xc8 && // JPG
74
+ marker !== 0xcc; // DAC
75
+ if (isFrameHeader) {
76
+ if (offset + 9 > header.length) {
77
+ return null;
78
+ }
79
+ const height = header.readUInt16BE(offset + 5);
80
+ const width = header.readUInt16BE(offset + 7);
81
+ return width > 0 && height > 0 ? { width, height } : null;
82
+ }
83
+ offset += 2 + segmentLength;
84
+ }
85
+ return null;
86
+ }
87
+
88
+ export async function getImageDimensions(
89
+ filePath: string,
90
+ ): Promise<ImageDimensions | null> {
91
+ let header: Buffer;
92
+ try {
93
+ header = await readHeader(filePath);
94
+ } catch {
95
+ return null;
96
+ }
97
+ if (header.length >= 8 && header.subarray(0, 8).equals(PNG_SIGNATURE)) {
98
+ return parsePngDimensions(header);
99
+ }
100
+ if (header.length >= 10 && header.toString("latin1", 0, 3) === "GIF") {
101
+ return parseGifDimensions(header);
102
+ }
103
+ if (
104
+ header.length >= 3 &&
105
+ header[0] === 0xff &&
106
+ header[1] === 0xd8 &&
107
+ header[2] === 0xff
108
+ ) {
109
+ return parseJpegDimensions(header);
110
+ }
111
+ return null;
112
+ }
@@ -0,0 +1,6 @@
1
+ const send = jest.fn().mockResolvedValue({});
2
+ module.exports = {
3
+ S3Client: jest.fn(() => ({ send })),
4
+ PutObjectCommand: jest.fn((input) => ({ input })),
5
+ __send: send,
6
+ };
@@ -0,0 +1,3 @@
1
+ module.exports = {
2
+ getSignedUrl: jest.fn().mockResolvedValue("https://signed.example.com/put-object"),
3
+ };