poad 2.14.1 → 2.15.0

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/global/start.js CHANGED
@@ -105,7 +105,8 @@ module.exports = async (args = {}) => {
105
105
  // toujours), puis seed.sql sur une base neuve
106
106
  const migrations = require('../utils/migrations');
107
107
  const { seedFile, runSeed } = require('../utils/seed');
108
- const hasMigrations = migrations.files(root).list.length > 0;
108
+ // Migrations, ou requêtes nommées (poad/queries) à synchroniser
109
+ const hasMigrations = migrations.files(root).list.length > 0 || require('../utils/queries').read(root).queries.length > 0;
109
110
  const migrate = hasMigrations && (migrations.autoMigrate(config) || args.forceMigrate);
110
111
  const seed = fresh && fsSync.existsSync(seedFile(root));
111
112
  if (hasMigrations && !migrate) console.log(chalk.grey(' auto_migrate is off: run "poad migrate" to apply pending migrations.'));
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.14.1",
4
- "engine": "0.7.2",
3
+ "version": "2.15.0",
4
+ "engine": "0.8.0",
5
5
  "main": "index.js",
6
6
  "license": "MIT",
7
7
  "bin": {
package/project/cli.js CHANGED
@@ -16,7 +16,11 @@ module.exports = {
16
16
  seed: 'Apply poad/seed.sql (development data)',
17
17
  },
18
18
  upgrade: 'Upgrade the engine of the project (backs up poad/ first): upgrade, upgrade to=<version>, upgrade --rollback, upgrade --list (--yes outside a terminal)',
19
- migrate: 'Apply pending migrations of poad/migrations (poad start does it too)',
19
+ gen: {
20
+ description: 'Generators: gen types (TypeScript types of the database)',
21
+ types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts)',
22
+ },
23
+ migrate: 'Apply pending migrations of poad/migrations and named queries of poad/queries (poad start does it too)',
20
24
  migration: 'Database migrations: migration new <name>, migration list',
21
25
  /* status: `[AI] Vérification du statut de l'environnement`,
22
26
  gen: {
@@ -0,0 +1,8 @@
1
+ // poad gen : aide des générateurs
2
+ module.exports = async () => {
3
+ const chalk = require('chalk-v2');
4
+ console.log(`${chalk.bold(' Usage :')}`);
5
+ console.log(' ');
6
+ console.log(` ${chalk.cyanBright('poad gen types')} TypeScript types of the database for createClient<Database>() (out=src/types/database.ts)`);
7
+ console.log(' ');
8
+ };
@@ -0,0 +1,43 @@
1
+ // poad gen types : types TypeScript du schéma de la base, pour
2
+ // createClient<Database>(url, anonKey). Le service data du projet les produit
3
+ // à partir de ce qu'il lit dans Postgres (/rest/v1/types.ts) ; le CLI les
4
+ // écrit dans src/types/database.ts (ou out=<chemin>).
5
+ // À relancer après une migration qui change les tables ou les fonctions.
6
+ module.exports = async (args = {}) => {
7
+ const chalk = require('chalk-v2');
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { findPoadDir } = require('../../utils/findpoad');
11
+ const { isDockerExist } = require('../../utils/docker');
12
+ const { readConfig } = require('../../utils/config');
13
+ const { supportsData } = require('../../utils/engine');
14
+
15
+ const root = findPoadDir(process.cwd());
16
+ if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
17
+ const config = readConfig(root);
18
+ if (!supportsData(config)) {
19
+ process.exitCode = 1;
20
+ return console.log(chalk.redBright(`Engine ${config.engine} has no data service: "poad upgrade" to 0.8.0 or later.`));
21
+ }
22
+ if (!(await isDockerExist(config.project_uuid))) {
23
+ process.exitCode = 1;
24
+ return console.log(chalk.redBright('The project is not started: run "poad start".'));
25
+ }
26
+ const out = path.resolve(path.dirname(path.dirname(root)), String(args.out || path.join('src', 'types', 'database.ts')));
27
+ const url = `http://localhost:${config.web.port}/rest/v1/types.ts`;
28
+ let text;
29
+ try {
30
+ const res = await fetch(url, { headers: { apikey: config.auth.service, authorization: `Bearer ${config.auth.service}` } });
31
+ text = await res.text();
32
+ if (!res.ok) throw new Error(`HTTP ${res.status} ${text.slice(0, 200)}`);
33
+ } catch (err) {
34
+ process.exitCode = 1;
35
+ return console.log(chalk.redBright(`Types not generated: ${err.message}`));
36
+ }
37
+ fs.mkdirSync(path.dirname(out), { recursive: true });
38
+ const before = fs.existsSync(out) ? fs.readFileSync(out, 'utf-8') : null;
39
+ fs.writeFileSync(out, text);
40
+ const tables = (text.match(/^ {6}\w+: \{$/gm) || []).length;
41
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(path.relative(process.cwd(), out))}${before === text ? chalk.grey(' (unchanged)') : ''}`);
42
+ console.log(chalk.grey(` ${tables} table(s). Use it with: createClient<Database>(url, anonKey)`));
43
+ };
package/utils/engine.js CHANGED
@@ -23,7 +23,21 @@ const storageInfo = (config) => {
23
23
  };
24
24
  };
25
25
 
26
- module.exports = { usesMinio, storageInfo };
26
+ // Engine 0.8.0 et plus : service data (/rest/v1) avec sa documentation
27
+ const supportsData = (config) => {
28
+ const [major, minor] = String(config.engine || '').split('.').map(Number);
29
+ return major > 0 || minor >= 8;
30
+ };
31
+
32
+ const dataInfo = (config) =>
33
+ supportsData(config)
34
+ ? {
35
+ 'REST URL': `http://localhost:${config.web.port}/rest/v1`,
36
+ 'API docs': `http://localhost:${config.web.port}/rest/v1/docs#apikey=${config.auth.anon}`,
37
+ }
38
+ : {};
39
+
40
+ module.exports = { usesMinio, storageInfo, supportsData, dataInfo };
27
41
 
28
42
  // Projet resté sur un engine plus ancien que celui du CLI : propose de mettre
29
43
  // à jour `engine` dans config.toml. La mise à jour migre poad/data : le projet
@@ -36,5 +36,22 @@ module.exports = async (root, config, { quietWhenNone = false } = {}) => {
36
36
  }
37
37
  if (applied.length) console.log(chalk.bold(` ${applied.length} migration(s) applied.`));
38
38
  else if (!quietWhenNone) console.log(chalk.grey(` Database up to date (${state.list.length} migration(s)).`));
39
- return true;
39
+
40
+ // Requêtes nommées (poad/queries) : des fonctions queries.<nom>
41
+ const qr = result.queries || { applied: [], dropped: [], errors: [] };
42
+ const qdir = rel(require('./queries').dir(root));
43
+ if (qr.applied.length) console.log(`${chalk.greenBright('✔')} ${chalk.bold(`${qdir}`)} ${chalk.grey(`: ${qr.applied.join(', ')}`)}`);
44
+ if (qr.dropped.length) console.log(chalk.grey(` Named queries removed (no file any more): ${qr.dropped.join(', ')}`));
45
+ for (const e of qr.errors) {
46
+ console.log(`${chalk.redBright('✖')} ${chalk.bold(`${qdir}/${e.file}`)}`);
47
+ console.log(chalk.redBright(` ${e.message}`));
48
+ }
49
+
50
+ // Tables exposées sans RLS : lisibles par tous avec la clé anon
51
+ for (const t of result.unprotected || []) {
52
+ const who = [t.anon && 'anon', t.authenticated && 'authenticated'].filter(Boolean).join(' and ');
53
+ console.log(chalk.yellowBright(` ⚠ ${t.schema}.${t.name}: row level security is off, so ${who} can read${t.anon_write ? ' and change' : ''} every row.`));
54
+ console.log(chalk.grey(` alter table ${t.schema}.${t.name} enable row level security; (then add policies)`));
55
+ }
56
+ return qr.errors.length === 0;
40
57
  };
@@ -143,13 +143,43 @@ async function migrate(root, config, { onApply } = {}) {
143
143
  return { applied, failed: { migration: m, message: `${err.message}${where}` }, state };
144
144
  }
145
145
  }
146
- return { applied, failed: null, state };
146
+ // Après les migrations : requêtes nommées (poad/queries), puis les tables
147
+ // exposées sans RLS
148
+ const queries = await require('./queries').sync(root, client);
149
+ const unprotected = await unprotectedTables(client, exposedSchemas(config));
150
+ return { applied, failed: null, state, queries, unprotected };
147
151
  } finally {
148
152
  await client.query('select pg_advisory_unlock($1)', [LOCK_ID]).catch(() => {});
149
153
  await client.end().catch(() => {});
150
154
  }
151
155
  }
152
156
 
157
+ /** Schémas servis par /rest/v1 : [data] schemas de config.toml, public par défaut */
158
+ const exposedSchemas = (config) => {
159
+ const s = config.data && config.data.schemas;
160
+ return Array.isArray(s) && s.length ? s.map(String) : ['public'];
161
+ };
162
+
163
+ /**
164
+ * Tables exposées sans RLS qu'anon ou authenticated peuvent lire : par défaut,
165
+ * le schéma public donne tous les droits à ces rôles, donc une table sans RLS
166
+ * est lisible (et modifiable) par n'importe qui avec la clé anon.
167
+ */
168
+ async function unprotectedTables(client, schemas) {
169
+ const { rows } = await client.query(
170
+ `select n.nspname as schema, c.relname as name,
171
+ has_table_privilege('anon', c.oid, 'select') as anon,
172
+ has_table_privilege('authenticated', c.oid, 'select') as authenticated,
173
+ has_table_privilege('anon', c.oid, 'insert') or has_table_privilege('anon', c.oid, 'update') or has_table_privilege('anon', c.oid, 'delete') as anon_write
174
+ from pg_class c join pg_namespace n on n.oid = c.relnamespace
175
+ where n.nspname = any($1) and c.relkind in ('r', 'p') and not c.relrowsecurity
176
+ and (has_table_privilege('anon', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'select'))
177
+ order by 1, 2`,
178
+ [schemas],
179
+ );
180
+ return rows;
181
+ }
182
+
153
183
  /** Attend que la base accepte les connexions (démarrage de l'engine) */
154
184
  async function waitForDb(config, seconds = 90) {
155
185
  for (let i = 0; i < seconds; i++) {
@@ -186,4 +216,4 @@ async function waitForServices(config, seconds = 90) {
186
216
  /** Les migrations s'appliquent-elles à poad start ? ([db] auto_migrate, vrai par défaut) */
187
217
  const autoMigrate = (config) => !(config.db && config.db.auto_migrate === false);
188
218
 
189
- module.exports = { dir, files, create, status, migrate, connect, waitForDb, waitForServices, autoMigrate, timestamp, FILE_RE };
219
+ module.exports = { dir, files, create, status, migrate, connect, waitForDb, waitForServices, autoMigrate, timestamp, exposedSchemas, unprotectedTables, FILE_RE };
@@ -0,0 +1,164 @@
1
+ // Requêtes SQL nommées : poad/queries/<nom>.sql devient la fonction
2
+ // queries.<nom>, appelée depuis le front avec poad.query('<nom>', { … }).
3
+ // Le SQL reste côté serveur, le front n'envoie que des arguments : c'est la
4
+ // façon sûre d'écrire du SQL pour le navigateur. La fonction s'exécute avec
5
+ // les droits de l'appelant (security invoker) : le RLS s'applique.
6
+ //
7
+ // -- @description Les auteurs qui ont le plus de notes
8
+ // -- @param limit int = 10
9
+ // -- @param since timestamptz
10
+ // select p.name, count(*) as notes
11
+ // from profiles p join notes n on n.author_id = p.id
12
+ // where n.created_at >= :since
13
+ // group by p.name order by notes desc limit :limit
14
+ //
15
+ // Les colonnes du résultat (et leurs types) sont demandées à Postgres. Les
16
+ // fonctions sont recréées à chaque poad migrate (et poad start) ; celles dont
17
+ // le fichier a disparu sont supprimées. `-- @volatile` permet une requête qui
18
+ // écrit (par défaut : stable, lecture seule).
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+
22
+ const NAME_RE = /^[a-z_][a-z0-9_]*$/;
23
+ const SCHEMA = 'queries';
24
+
25
+ const dir = (root) => path.join(path.dirname(root), 'queries');
26
+
27
+ const q = (id) => `"${id.replace(/"/g, '""')}"`;
28
+
29
+ /** Lit et analyse les fichiers ; renvoie { queries, errors } */
30
+ function read(root) {
31
+ const d = dir(root);
32
+ if (!fs.existsSync(d)) return { queries: [], errors: [] };
33
+ const queries = [];
34
+ const errors = [];
35
+ for (const file of fs.readdirSync(d).filter((f) => f.endsWith('.sql')).sort()) {
36
+ const name = file.replace(/\.sql$/, '');
37
+ try {
38
+ if (!NAME_RE.test(name)) throw new Error('nom invalide : lettres minuscules, chiffres et _');
39
+ queries.push(parse(name, fs.readFileSync(path.join(d, file), 'utf-8')));
40
+ } catch (err) {
41
+ errors.push({ file, message: err.message });
42
+ }
43
+ }
44
+ return { queries, errors };
45
+ }
46
+
47
+ function parse(name, text) {
48
+ const params = [];
49
+ let description = null;
50
+ let volatile = false;
51
+ for (const line of text.split(/\r?\n/)) {
52
+ const m = /^\s*--\s*@(\w+)\s*(.*)$/.exec(line);
53
+ if (!m) continue;
54
+ const [, tag, rest] = m;
55
+ if (tag === 'description') description = rest.trim();
56
+ else if (tag === 'volatile') volatile = true;
57
+ else if (tag === 'param') {
58
+ const p = /^([a-z_][a-z0-9_]*)\s+([^=]+?)\s*(?:=\s*(.+))?$/i.exec(rest.trim());
59
+ if (!p) throw new Error(`@param illisible : « ${rest.trim()} » (attendu : @param nom type [= défaut])`);
60
+ if (params.some((x) => x.name === p[1])) throw new Error(`@param ${p[1]} déclaré deux fois`);
61
+ params.push({ name: p[1], type: p[2].trim(), default: p[3] === undefined ? null : p[3].trim() });
62
+ } else throw new Error(`annotation inconnue : @${tag} (@description, @param, @volatile)`);
63
+ }
64
+ // Les paramètres sans valeur par défaut d'abord (contrainte de Postgres)
65
+ const firstDefault = params.findIndex((p) => p.default !== null);
66
+ if (firstDefault >= 0 && params.slice(firstDefault).some((p) => p.default === null))
67
+ throw new Error('les @param avec une valeur par défaut doivent venir après les autres');
68
+
69
+ // :nom → $n, hors chaînes, identifiants entre guillemets, commentaires et ::casts
70
+ const used = new Set();
71
+ let body = '';
72
+ let i = 0;
73
+ while (i < text.length) {
74
+ const c = text[i];
75
+ const rest = text.slice(i);
76
+ let m;
77
+ if ((m = /^--[^\n]*/.exec(rest)) || (m = /^\/\*[\s\S]*?\*\//.exec(rest)) || (m = /^'(?:[^']|'')*'/.exec(rest)) || (m = /^"(?:[^"]|"")*"/.exec(rest)) || (m = /^\$([a-z_]*)\$[\s\S]*?\$\1\$/i.exec(rest))) {
78
+ body += m[0].startsWith('--') ? '' : m[0];
79
+ i += m[0].length;
80
+ } else if ((m = /^::/.exec(rest))) {
81
+ body += '::';
82
+ i += 2;
83
+ } else if ((m = /^:([a-z_][a-z0-9_]*)/i.exec(rest))) {
84
+ const idx = params.findIndex((p) => p.name === m[1]);
85
+ if (idx < 0) throw new Error(`:${m[1]} utilisé sans @param ${m[1]}`);
86
+ used.add(m[1]);
87
+ body += `$${idx + 1}`;
88
+ i += m[0].length;
89
+ } else {
90
+ body += c;
91
+ i += 1;
92
+ }
93
+ }
94
+ body = body.trim().replace(/;\s*$/, '');
95
+ if (!body) throw new Error('requête vide');
96
+ if (/;/.test(body.replace(/'(?:[^']|'')*'/g, ''))) throw new Error('une seule instruction SQL par fichier');
97
+ const unused = params.filter((p) => !used.has(p.name)).map((p) => p.name);
98
+ if (unused.length) throw new Error(`@param déclaré mais pas utilisé : ${unused.join(', ')}`);
99
+ return { name, params, description, volatile, body };
100
+ }
101
+
102
+ /**
103
+ * Crée ou recrée les fonctions de queries, supprime celles sans fichier.
104
+ * Renvoie { applied: [noms], dropped: [noms], errors: [{ file, message }] }.
105
+ */
106
+ async function sync(root, client) {
107
+ const { queries, errors } = read(root);
108
+ const applied = [];
109
+ const existing = (
110
+ await client.query(`select p.proname as name, pg_get_function_identity_arguments(p.oid) as args from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname = $1`, [SCHEMA])
111
+ ).rows;
112
+ if (!queries.length && !existing.length) return { applied, dropped: [], errors };
113
+
114
+ await client.query(`create schema if not exists ${SCHEMA}`);
115
+ await client.query(`grant usage on schema ${SCHEMA} to anon, authenticated, service_role`);
116
+
117
+ for (const query of queries) {
118
+ try {
119
+ // Colonnes du résultat, telles que Postgres les voit
120
+ await client.query('begin');
121
+ const probe = `select * from (${query.body}) r limit 0`;
122
+ // Sonde sans valeurs : chaque paramètre devient un null de son type
123
+ const typed = query.params.map((p) => `(null::${p.type})`);
124
+ const res = await client.query({ text: probe.replace(/\$(\d+)/g, (_, n) => typed[Number(n) - 1]), values: [], rowMode: 'array' });
125
+ await client.query('rollback');
126
+ if (!res.fields.length) throw new Error('la requête ne renvoie aucune colonne');
127
+ const oids = res.fields.map((f) => f.dataTypeID);
128
+ const types = (await client.query('select oid, format_type(oid, null) as t from pg_type where oid = any($1)', [oids])).rows;
129
+ const typeOf = new Map(types.map((r) => [r.oid, r.t]));
130
+ const seen = new Set();
131
+ const columns = res.fields.map((f) => {
132
+ if (seen.has(f.name)) throw new Error(`colonne ${f.name} en double dans le résultat : donnez-lui un alias`);
133
+ seen.add(f.name);
134
+ return `${q(f.name)} ${typeOf.get(f.dataTypeID) || 'text'}`;
135
+ });
136
+ const args = query.params.map((p) => `${q(p.name)} ${p.type}${p.default !== null ? ` default ${p.default}` : ''}`).join(', ');
137
+ const fn = `${SCHEMA}.${q(query.name)}`;
138
+ await client.query('begin');
139
+ for (const e of existing.filter((x) => x.name === query.name)) await client.query(`drop function ${fn}(${e.args})`);
140
+ await client.query(
141
+ `create function ${fn}(${args}) returns table (${columns.join(', ')}) language sql ${query.volatile ? 'volatile' : 'stable'} security invoker as $poad$\n${query.body}\n$poad$`,
142
+ );
143
+ if (query.description) await client.query(`comment on function ${fn}(${query.params.map((p) => p.type).join(', ')}) is ${client.escapeLiteral(query.description)}`);
144
+ await client.query(`grant execute on function ${fn}(${query.params.map((p) => p.type).join(', ')}) to anon, authenticated, service_role`);
145
+ await client.query('commit');
146
+ applied.push(query.name);
147
+ } catch (err) {
148
+ await client.query('rollback').catch(() => {});
149
+ errors.push({ file: `${query.name}.sql`, message: err.message });
150
+ }
151
+ }
152
+
153
+ // Fichiers disparus : fonctions supprimées (celles en erreur sont gardées)
154
+ const keep = new Set([...queries.map((x) => x.name), ...errors.map((e) => e.file.replace(/\.sql$/, ''))]);
155
+ const dropped = [];
156
+ for (const e of existing) {
157
+ if (keep.has(e.name)) continue;
158
+ await client.query(`drop function if exists ${SCHEMA}.${q(e.name)}(${e.args})`);
159
+ dropped.push(e.name);
160
+ }
161
+ return { applied, dropped, errors };
162
+ }
163
+
164
+ module.exports = { dir, read, parse, sync, SCHEMA };
package/utils/report.js CHANGED
@@ -23,7 +23,7 @@ async function migrationsLine(root, config) {
23
23
  async function printProject(root, config) {
24
24
  const chalk = require('chalk-v2');
25
25
  const prettyoutput = require('prettyoutput');
26
- const { storageInfo } = require('./engine');
26
+ const { storageInfo, dataInfo } = require('./engine');
27
27
  const mail = require('./mail');
28
28
  console.log(chalk.bold('POAD project'));
29
29
  console.log(' ');
@@ -32,6 +32,7 @@ async function printProject(root, config) {
32
32
  'API URL': `http://localhost:${config.web.port}`,
33
33
  'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
34
34
  ...storageInfo(config),
35
+ ...dataInfo(config),
35
36
  ...(mail.usesMailpit(config) ? {} : { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }),
36
37
  'JWT secret': `${config.auth.secret}`,
37
38
  'anon key': config.auth.anon,