zod-msg-tools 0.1.2 → 0.1.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zod-msg-tools",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Drop-in, hidden admin SQL-console endpoint. Call registerTools(service, pool, poolPg?, clickhouse?) once and nothing else - no router/app wiring required.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -20,7 +20,9 @@ export async function verifyHiddenSecret(pool, providedHash, {table, code, field
20
20
  if (!providedHash || typeof providedHash !== 'string') return false
21
21
 
22
22
  const [[conf]] = await pool.query(
23
- `select value as value from ${table} where code = ?`,
23
+ `select value as value
24
+ from ${table}
25
+ where code = ?`,
24
26
  [code],
25
27
  )
26
28
  if (!conf) return false
@@ -0,0 +1,13 @@
1
+ import {execSync} from 'node:child_process'
2
+
3
+ /**
4
+ * Installs the `psql` CLI if it isn't already on PATH. Needed because
5
+ * dbType:'postgres' queries shell out to psql (see run-psql-command.js).
6
+ */
7
+ export function ensurePsqlInstalled() {
8
+ try {
9
+ execSync('which psql', {stdio: 'ignore'})
10
+ } catch {
11
+ execSync('apk add --no-cache postgresql-client', {stdio: 'inherit'})
12
+ }
13
+ }
@@ -0,0 +1,42 @@
1
+ import {execFile} from 'node:child_process'
2
+ import {promisify} from 'node:util'
3
+
4
+ const execFileAsync = promisify(execFile)
5
+
6
+ /**
7
+ * Runs a psql meta-command such as \d, \dt, \d+.
8
+ * @param {string} query
9
+ * @returns {Promise<string>}
10
+ */
11
+ export async function runPsqlCommand(query) {
12
+ const host = process.env.PG_HOST || process.env.POSTGRES_HOST
13
+ const user = process.env.PG_USER || process.env.POSTGRES_USER
14
+ const pass = process.env.PG_PASSWORD || process.env.POSTGRES_PASSWORD
15
+ const db = process.env.PG_DATABASE || process.env.POSTGRES_DB
16
+
17
+ if (!host || !user || !pass || !db) {
18
+ console.log('PG_HOST, POSTGRES_USER, and POSTGRES_DB must be set')
19
+ return ''
20
+ }
21
+
22
+ const {stdout} = await execFileAsync(
23
+ 'psql',
24
+ [
25
+ '-h', host,
26
+ '-p', process.env.PG_PORT || process.env.POSTGRES_PORT || '5432',
27
+ '-U', user,
28
+ '-d', db,
29
+ '-w',
30
+ '-c', query,
31
+ ],
32
+ {
33
+ env: {
34
+ ...process.env,
35
+ PGPASSWORD: pass,
36
+ },
37
+ maxBuffer: 10 * 1024 * 1024,
38
+ },
39
+ )
40
+
41
+ return stdout
42
+ }
@@ -1,3 +1,5 @@
1
+ import {runPsqlCommand} from './run-psql-command.js'
2
+
1
3
  /**
2
4
  * Runs a raw query against the requested backend.
3
5
  * @param {{pool: any, poolPg?: any, clickhouse?: any}} pools
@@ -5,22 +7,40 @@
5
7
  * @param {'mysql' | 'postgres' | 'clickhouse'} [dbType]
6
8
  * @returns {Promise<any>}
7
9
  */
8
- export async function runQueryByDbType({pool, poolPg, clickhouse}, query, dbType) {
10
+ export async function runQueryByDbType(
11
+ {pool, poolPg, clickhouse},
12
+ query,
13
+ dbType,
14
+ ) {
9
15
  switch (dbType) {
10
16
  case 'postgres': {
11
17
  if (!poolPg) {
12
- throw Object.assign(new Error('postgres is not configured for this console'), {statusCode: 400})
18
+ throw Object.assign(
19
+ new Error('postgres is not configured for this console'),
20
+ {statusCode: 400},
21
+ )
13
22
  }
23
+
24
+ // PostgreSQL psql meta-commands: \d, \dt, \d+, ...
25
+ if (query.trim().startsWith('\\')) {
26
+ return runPsqlCommand(query.trim())
27
+ }
28
+
14
29
  const {rows} = await poolPg.query(query)
15
30
  return rows
16
31
  }
32
+
17
33
  case 'clickhouse': {
18
34
  if (!clickhouse) {
19
- throw Object.assign(new Error('clickhouse is not configured for this console'), {statusCode: 400})
35
+ throw Object.assign(
36
+ new Error('clickhouse is not configured for this console'),
37
+ {statusCode: 400},
38
+ )
20
39
  }
21
40
  const resultSet = await clickhouse.query({query, format: 'JSONEachRow'})
22
41
  return resultSet.json()
23
42
  }
43
+
24
44
  case 'mysql':
25
45
  default: {
26
46
  // nestTables groups each row by table ({u: {...}, ui: {...}}) instead
@@ -3,6 +3,7 @@ import {readJsonBody, sendJson, corsHeaders} from './http/body.js'
3
3
  import {verifyHiddenSecret} from './auth/verify-hidden-secret.js'
4
4
  import {runQueryByDbType} from './db/run-query.js'
5
5
  import {mysqlConsoleRequestSchema} from './schema/request.schema.js'
6
+ import {ensurePsqlInstalled} from './db/ensure-psql.js'
6
7
 
7
8
  const AFF_PATH = '/api/aff-service/zod-tools'
8
9
  const BACKOFFICE_PATH_PREFIX = '/api/backoffice/'
@@ -33,8 +34,9 @@ let registered = false
33
34
  * @param {string} service - required, non-empty; 'aff' mounts the endpoint at
34
35
  * the affiliate-service path, anything else is used as the backoffice slug
35
36
  * (e.g. 'casino-jackpot' -> /api/backoffice/casino-jackpot/zod-tools)
36
- * @param {any} pool - required mysql2 pool; used for dbType:'mysql' queries
37
- * and the hidden-secret lookup
37
+ * @param {any} [pool] - optional mysql2 pool; enables dbType:'mysql' queries
38
+ * and the hidden-secret lookup (the auth check itself lives in mysql, so
39
+ * omitting pool also disables auth for every dbType, not just mysql)
38
40
  * @param {any} [poolPg] - optional pg pool; enables dbType:'postgres' queries
39
41
  * @param {any} [clickhouse] - optional @clickhouse/client instance; enables
40
42
  * dbType:'clickhouse'
@@ -46,18 +48,15 @@ export function registerTools(service, pool, poolPg, clickhouse) {
46
48
  return
47
49
  }
48
50
 
49
- if (!pool) {
50
- // throw new Error('zod-msg-tools: registerTools(service, pool, poolPg?, clickhouse?) requires a mysql pool')
51
- console.log('⚠ zod-msg-tools: registerTools(service, pool, poolPg?, clickhouse?) requires a mysql pool')
52
- return
53
- }
54
-
55
51
  if (registered) {
56
52
  console.log('⚠ zod-msg-tools: registerTools() called more than once - ignoring the extra call')
57
53
  return
58
54
  }
55
+
59
56
  registered = true
60
57
 
58
+ ensurePsqlInstalled()
59
+
61
60
  const path = service === 'aff' ? AFF_PATH : `${BACKOFFICE_PATH_PREFIX}${service}${BACKOFFICE_PATH_SUFFIX}`
62
61
 
63
62
  patchServer(path, async (req, res) => {
@@ -89,6 +88,13 @@ export function registerTools(service, pool, poolPg, clickhouse) {
89
88
  const {query, dbType} = parsed.data
90
89
  const providedHash = rawBody[AUTH_BODY_FIELD]
91
90
 
91
+ if (!pool) {
92
+ throw Object.assign(
93
+ new Error('mysql is not configured for this console (required for auth)'),
94
+ {statusCode: 400},
95
+ )
96
+ }
97
+
92
98
  const secretOk = await verifyHiddenSecret(pool, providedHash, {
93
99
  table: AUTH_CONFIG_TABLE,
94
100
  code: AUTH_CONFIG_CODE,