poad 2.64.0 → 2.69.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.64.0",
3
+ "version": "2.69.0",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.5.0",
6
6
  "main": "index.js",
package/poad.js CHANGED
@@ -224,7 +224,8 @@ const parseCommandArgs = (commands, args) => {
224
224
 
225
225
  for (let i = 0; i < args.length; i++) {
226
226
  const currentPath = args[i];
227
- if (currentCommands[currentPath]) {
227
+ // Propre à l'objet seulement : sinon « poad source link » trouverait String.prototype.link
228
+ if (currentCommands && typeof currentCommands === 'object' && Object.prototype.hasOwnProperty.call(currentCommands, currentPath) && currentCommands[currentPath]) {
228
229
  // Si le chemin est valide, ajoute à dir et descend dans la structure
229
230
  dir.push(currentPath);
230
231
  currentCommands = currentCommands[currentPath];
package/project/cli.js CHANGED
@@ -67,7 +67,7 @@ module.exports = {
67
67
  logs: 'Unified logs of the project, every service, with filters (level, since, request, flow, function, AI…) and -f',
68
68
  gen: {
69
69
  description: 'Generators of TypeScript types: the database, the public variables',
70
- types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts)',
70
+ types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts, role=authenticated|anon|service_role)',
71
71
  env: 'TypeScript types of the public variables (PUBLIC_*) for poad.env (out=src/types/poad-env.ts)',
72
72
  },
73
73
  migrate: 'Apply pending migrations of poad/migrations and named queries of poad/queries (poad start does it too)',
@@ -76,7 +76,7 @@ module.exports = {
76
76
  function: 'Alias of poad functions',
77
77
  flows: 'Flows of the project (automations in poad/flows/<name>.json, engine 0.18.0+, needs Valkey): new, list, run, runs, show, cancel; --env <name> for poad.io',
78
78
  flow: 'Alias of poad flows',
79
- source: 'Sources of the project (tables kept up to date from a URL or an uploaded file, poad/sources/<name>.yaml, engine 0.64.0+): ls, refresh <name> [--force], import <file> [--table <t>], pull <name>; --env <name> for poad.io',
79
+ source: 'Sources of the project (tables kept up to date from a URL or an uploaded file, poad/sources/<name>.yaml, engine 0.64.0+): ls, refresh <name> [--force], import <file> [--table <t>], link <table> (linked table of another PostgreSQL database, or remote table over a CSV, JSON, JSON-L, GeoJSON or Parquet file: --url or --storage, engine 0.67.0+), test <name>, pull <name>; --env <name> for poad.io',
80
80
  sources: 'Alias of poad source',
81
81
  /* status: `[AI] Vérification du statut de l'environnement`,
82
82
  gen: {
package/project/deploy.js CHANGED
@@ -7,6 +7,9 @@
7
7
  // x-poad-dry-run 1 avec --dry-run : le serveur dit ce qu'il ferait, rien ne change
8
8
  // réponse : { deploy_id?, status?, migrations: { applied, pending, errors }, warnings }
9
9
  // warnings : migrations qui perdent des données (drop table, truncate…), signalées, jamais refusées
10
+ // api_exposure : fonctions et vues que l'API ne sert pas à anon ni à authenticated (SECURITY DEFINER, vues
11
+ // sans security_invoker, vues matérialisées), dans la base et dans les migrations en attente, avec ce que
12
+ // l'engine de l'environnement en fait et le correctif de chacune (poad.io 0.66.0+), jamais bloquant
10
13
  // asynchrone (deploy_id et état non terminé) : GET …/deploys/:deploy_id jusqu'à la fin
11
14
  //
12
15
  // Production (main) : résumé puis confirmation, sauf --yes (obligatoire hors
@@ -36,9 +39,22 @@ function summarize(d = {}) {
36
39
  // Signalé, jamais bloquant : migrations qui perdent des données (drop table, truncate…)
37
40
  warnings: (Array.isArray(d.warnings) ? d.warnings : []).map((w) => ({ message: String((w && w.message) || ''), files: Array.isArray(w && w.files) ? w.files.map(String) : [] })),
38
41
  failed: errors.length > 0 || FAILED.includes(status),
42
+ api_exposure: exposureOf(d.api_exposure),
39
43
  };
40
44
  }
41
45
 
46
+ /** Avertissement de l'API (poad.io) ramené à la règle du CLI (utils/api-exposure) : textes en anglais */
47
+ function exposureOf(x) {
48
+ if (!x || typeof x !== 'object' || !Array.isArray(x.items)) return null;
49
+ const items = x.items
50
+ .filter((i) => i && typeof i.schema === 'string' && typeof i.name === 'string')
51
+ .map((i) => ({ kind: String(i.kind || ''), schema: i.schema, name: i.name, signature: typeof i.signature === 'string' ? i.signature : undefined, reason: String(i.reason || ''), anon: Array.isArray(i.roles) ? i.roles.includes('anon') : true, authenticated: Array.isArray(i.roles) ? i.roles.includes('authenticated') : true, source: i.source, file: i.file }));
52
+ const out = require('../utils/api-exposure').impact({ current: x.current || null, target: x.target || x.current || null, items });
53
+ // La décision du serveur prime (il connaît la version de l'environnement)
54
+ if (typeof x.change === 'string') out.change = x.change;
55
+ return out;
56
+ }
57
+
42
58
  function gitState(dir) {
43
59
  const { spawnSync } = require('child_process');
44
60
  const git = (a) => spawnSync('git', a, { cwd: dir, encoding: 'utf8', timeout: 10000 });
@@ -142,6 +158,8 @@ module.exports = (args, raw) =>
142
158
  for (const f of w.files) out.log(` ${chalk.yellow(f)}`);
143
159
  }
144
160
  if (!m.applied.length && !m.pending.length && !m.errors.length) out.log(chalk.grey(' No migration to apply.'));
161
+ // Ce que l'API ne sert pas à anon ni à authenticated : jamais bloquant, toujours dit (avec le correctif)
162
+ for (const l of require('../utils/api-exposure').lines(result.api_exposure, chalk)) out.log(l);
145
163
  // Grosses références : après les migrations (les tables existent), envoi puis chargement
146
164
  let references = null;
147
165
  if (large.length && !dryRun && !result.failed) {
@@ -3,6 +3,9 @@
3
3
  // à partir de ce qu'il lit dans Postgres (/rest/v1/types.ts) ; le CLI les
4
4
  // écrit dans src/types/database.ts (ou out=<chemin>).
5
5
  // À relancer après une migration qui change les tables ou les fonctions.
6
+ // role=anon|authenticated (défaut : authenticated, ce que voit un front) ; role=service_role : aussi les fonctions
7
+ // SECURITY DEFINER, vues sans security_invoker et vues matérialisées, que l'API ne sert qu'à service_role (marquées
8
+ // « Réservé à service_role »), pour le code serveur (engine 0.66.0+).
6
9
  module.exports = async (args = {}) => {
7
10
  const chalk = require('chalk-v2');
8
11
  const fs = require('fs');
@@ -24,7 +27,12 @@ module.exports = async (args = {}) => {
24
27
  return console.log(chalk.redBright('The project is not started: run "poad start".'));
25
28
  }
26
29
  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`;
30
+ const role = String(args.role || 'authenticated');
31
+ if (!['anon', 'authenticated', 'service_role'].includes(role)) {
32
+ process.exitCode = 2;
33
+ return console.log(chalk.redBright('role: anon, authenticated or service_role.'));
34
+ }
35
+ const url = `http://localhost:${config.web.port}/rest/v1/types.ts?role=${role}`;
28
36
  let text;
29
37
  try {
30
38
  const res = await fetch(url, { headers: { apikey: config.auth.service, authorization: `Bearer ${config.auth.service}` } });
@@ -40,5 +48,5 @@ module.exports = async (args = {}) => {
40
48
  const tables = (text.match(/^ {6}\w+: \{$/gm) || []).length;
41
49
  const shown = path.relative(process.cwd(), out).startsWith('..') ? out : path.relative(process.cwd(), out);
42
50
  console.log(`${chalk.greenBright('✔')} ${chalk.bold(shown)}${before === text ? chalk.grey(' (unchanged)') : ''}`);
43
- console.log(chalk.grey(` ${tables} table(s). Use it with: createClient<Database>(url, anonKey)`));
51
+ console.log(chalk.grey(` ${tables} table(s), as seen by ${role}. Use it with: createClient<Database>(url, ${role === 'service_role' ? 'serviceKey' : 'anonKey'})`));
44
52
  };
package/project/source.js CHANGED
@@ -2,6 +2,15 @@
2
2
  // poad source refresh <nom> [--force] synchronise une source maintenant et suit son exécution
3
3
  // poad source import <fichier> [--table t] charge un fichier (CSV, JSON, GeoJSON, JSONL, gzip) dans une table :
4
4
  // source « Fichier envoyé » (nouvelle, ou nouvelle version d'une source envoyée)
5
+ // poad source link <table> --host h --database d --remote schéma.table --credential c [--sslmode m] [--port p] [--columns a,b]
6
+ // table liée (mode virtual, engine 0.66.0+) : une table d'une autre base PostgreSQL
7
+ // lue à chaque requête, rien n'est copié ; colonnes proposées par l'engine
8
+ // poad source link <table> --url https://… | --storage bucket/chemin [--format f] [--delimiter ;] [--no-header]
9
+ // [--encoding e] [--root a.b] [--columns a,b]
10
+ // table distante sur fichier (mode virtual, engine 0.67.0+) : CSV, JSON, JSON-L,
11
+ // GeoJSON ou Parquet lu par DuckDB dans Postgres à chaque requête, rien n'est copié
12
+ // poad source test <nom> table liée ou distante : vérifie l'adresse (garde des adresses internes),
13
+ // rebranche, lit une ligne par Postgres
5
14
  // poad source pull <nom> [--force] rapatrie la déclaration d'une source (créée dans la console
6
15
  // de poad.io avec --env) dans poad/sources/<nom>.yaml
7
16
  //
@@ -20,10 +29,136 @@
20
29
  const flows = require('./flows');
21
30
 
22
31
  const NAME_RE = /^(?:[a-z][a-z0-9-]{0,55}|[a-z_][a-z0-9_]{0,62})$/; // meta, sources.ts : SOURCE_NAME_RE (nom de table, ou d'avant 0.65.0)
32
+ /** Formats d'une source (meta : sources.ts FORMATS ; ics… lus par l'étape source-read 1.3.0, engine avec meta 1.43.0) */
33
+ const FORMATS = ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx'];
34
+
35
+ /** Ce que le lecteur d'un format a trouvé (réponse de /sources/sample) : une ligne, ou null. Pure. */
36
+ const describeReader = (sample) => {
37
+ const d = (sample && sample.details) || {};
38
+ const o = (sample && sample.options) || {};
39
+ const out = [];
40
+ if (d.sheet) out.push(`sheet "${d.sheet}"${Array.isArray(d.sheets) && d.sheets.length > 1 ? ` (of ${d.sheets.map((x) => `"${x}"`).join(', ')}; --sheet)` : ''}`);
41
+ if (d.header_row) out.push(`header on row ${d.header_row}`);
42
+ else if (o.header === false) out.push('no header row');
43
+ if (o.records) out.push(`records ${o.records}`);
44
+ if (o.expand && o.expand.until) out.push(`recurrences expanded until ${o.expand.until}`);
45
+ if (typeof d.events === 'number') out.push(`${d.events} event(s)`);
46
+ if (typeof d.placemarks === 'number') out.push(`${d.placemarks} placemark(s)`);
47
+ if (sample && sample.run_id) out.push(`read by source-read (run ${sample.run_id})`);
48
+ return out.length ? out.join(', ') : null;
49
+ };
50
+
23
51
  const POLL_MS = 1000;
24
52
  const TIMEOUT_MS = 30000;
25
53
  const FINAL = ['completed', 'failed', 'cancelled'];
26
- const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach] | import <file> [--table <table>] [--name <source>] | pull <name> [--force] [--stdout], and --env <name> | --project <id> for poad.io';
54
+ const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach] | import <file> [--table <table>] [--name <source>] | link <table> --host <host> --database <db> --remote <schema.table> --credential <name> | link <table> --url <https://…> | --storage <bucket>/<path> | test <name> | pull <name> [--force] [--stdout], and --env <name> | --project <id> for poad.io';
55
+ const LINK_USAGE = 'Usage: poad source link <table> --host <host> --database <db> --remote <schema.table> --credential <name> [--port <port>] [--sslmode require|verify-full|disable] [--columns <col,…>] [--env <name>]\n or: poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>] [--env <name>]';
56
+ const SSLMODES = ['require', 'verify-full', 'disable'];
57
+ /** Formats d'une table distante sur fichier (meta, engine 0.67.0 : lus par DuckDB) */
58
+ const REMOTE_FORMATS = ['csv', 'json', 'jsonl', 'geojson', 'parquet'];
59
+ const REMOTE_ENCODINGS = ['utf-8', 'latin-1', 'iso-8859-1', 'windows-1252', 'utf-16'];
60
+ const BUCKET_RE = /^[a-z0-9][a-z0-9._-]{0,62}$/;
61
+
62
+ /** Emplacement d'un fichier distant, sans query string ni identifiant : https://hôte/chemin ou storage://bucket/chemin. Pure. */
63
+ const remoteLocation = (o) => {
64
+ if (!o) return '';
65
+ if (o.storage && o.storage.bucket) return `storage://${o.storage.bucket}/${o.storage.path || ''}`;
66
+ if (!o.url) return '';
67
+ try {
68
+ const u = new URL(o.url);
69
+ return `${u.protocol}//${u.host}${u.pathname}`;
70
+ } catch {
71
+ return String(o.url).split(/[?#]/)[0];
72
+ }
73
+ };
74
+
75
+ /** « bucket/chemin/fichier.csv » → { bucket, path }, ou un message. Pure. */
76
+ const parseStorageRef = (raw) => {
77
+ const v = String(raw || '').replace(/^storage:\/\//, '').replace(/^\/+/, '');
78
+ const i = v.indexOf('/');
79
+ if (i <= 0 || i === v.length - 1) return '--storage takes <bucket>/<path> (an object of the project storage), e.g. donnees/arrets.geojson';
80
+ const bucket = v.slice(0, i);
81
+ const path = v.slice(i + 1);
82
+ if (!BUCKET_RE.test(bucket)) return `"${bucket}" is not a bucket name`;
83
+ if (path.split('/').some((p) => p === '' || p === '.' || p === '..') || /[\u0000-\u001f\\]/.test(path)) return `"${path.slice(0, 80)}" is not an object path`;
84
+ return { bucket, path };
85
+ };
86
+
87
+ /**
88
+ * Options de « poad source link » : table liée (--host…) ou table distante sur fichier (--url / --storage).
89
+ * Rend { ok: false, message } ou { ok: true, kind: 'postgres' | 'file', o }. Pure.
90
+ */
91
+ const parseLinkArgs = (words) => {
92
+ const o = { table: null, host: null, port: null, database: null, remote: null, credential: null, sslmode: null, columns: null, title: null, url: null, storage: null, format: null, delimiter: null, header: null, encoding: null, root: null };
93
+ const valued = { '--host': 'host', '--port': 'port', '--database': 'database', '--db': 'database', '--remote': 'remote', '--credential': 'credential', '--sslmode': 'sslmode', '--columns': 'columns', '--title': 'title', '--url': 'url', '--storage': 'storage', '--format': 'format', '--delimiter': 'delimiter', '--encoding': 'encoding', '--root': 'root' };
94
+ for (let i = 0; i < words.length; i++) {
95
+ const w = words[i];
96
+ const flag = valued[w];
97
+ if (flag) {
98
+ const v = words[++i];
99
+ if (v === undefined || (v.startsWith('--') && v.length > 2)) return { ok: false, message: `poad source link: ${w} needs a value.` };
100
+ o[flag] = v;
101
+ } else if (w === '--no-header') o.header = false;
102
+ else if (w === '--header') o.header = true;
103
+ else if (w === '--yes' || w === '-y') continue;
104
+ else if (w.startsWith('-')) return { ok: false, message: `poad source link: unknown option ${w}.\n${LINK_USAGE}`, usage: true };
105
+ else if (o.table === null) o.table = w.replace(/^public\./, '');
106
+ else return { ok: false, message: `poad source link: one table at a time ("${w}").` };
107
+ }
108
+ const file = o.url !== null || o.storage !== null;
109
+ if (!o.table) return { ok: false, message: LINK_USAGE, usage: true };
110
+ if (!/^[a-z_][a-z0-9_]{0,62}$/.test(o.table)) return { ok: false, message: `"${o.table}" is not a table name (a-z, 0-9 and "_", a letter or "_" first).` };
111
+ if (!file) {
112
+ for (const k of ['format', 'delimiter', 'encoding', 'root']) if (o[k] !== null) return { ok: false, message: `--${k} is for a file (--url or --storage).` };
113
+ if (o.header !== null) return { ok: false, message: '--header / --no-header are for a CSV file (--url or --storage).' };
114
+ if (!o.host || !o.database || !o.remote || !o.credential) return { ok: false, message: LINK_USAGE, usage: true };
115
+ o.sslmode = o.sslmode || 'require';
116
+ if (!SSLMODES.includes(o.sslmode)) return { ok: false, message: `--sslmode: ${SSLMODES.join(', ')}.` };
117
+ if (o.port !== null && !(Number.isInteger(Number(o.port)) && Number(o.port) >= 1 && Number(o.port) <= 65535)) return { ok: false, message: '--port: 1 to 65535.' };
118
+ return { ok: true, kind: 'postgres', o };
119
+ }
120
+ if (o.url !== null && o.storage !== null) return { ok: false, message: 'poad source link: --url or --storage, not both.' };
121
+ for (const k of ['host', 'port', 'database', 'remote', 'credential', 'sslmode']) if (o[k] !== null) return { ok: false, message: `--${k} is for a linked PostgreSQL table, not a file (--url or --storage).` };
122
+ if (o.url !== null) {
123
+ let u;
124
+ try {
125
+ u = new URL(o.url);
126
+ } catch {
127
+ return { ok: false, message: `--url: "${o.url.slice(0, 80)}" is not an address.` };
128
+ }
129
+ if (u.protocol !== 'https:' && u.protocol !== 'http:') return { ok: false, message: '--url: an http:// or https:// address.' };
130
+ if (u.username || u.password) return { ok: false, message: '--url: no user or password in the address.' };
131
+ } else {
132
+ const ref = parseStorageRef(o.storage);
133
+ if (typeof ref === 'string') return { ok: false, message: ref };
134
+ o.storage = ref;
135
+ }
136
+ if (o.format !== null && !REMOTE_FORMATS.includes(o.format)) return { ok: false, message: `--format: ${REMOTE_FORMATS.join(', ')} (got "${o.format}").` };
137
+ const csvOpt = o.delimiter !== null || o.header !== null || o.encoding !== null;
138
+ if (csvOpt && o.format !== null && o.format !== 'csv') return { ok: false, message: '--delimiter, --no-header and --encoding are for a CSV file.' };
139
+ if (o.delimiter !== null && !(o.delimiter.length === 1 || ['\\t', 'tab'].includes(o.delimiter))) return { ok: false, message: '--delimiter: one character (or tab).' };
140
+ if (o.encoding !== null && !REMOTE_ENCODINGS.includes(o.encoding.toLowerCase())) return { ok: false, message: `--encoding: ${REMOTE_ENCODINGS.join(', ')}.` };
141
+ if (o.root !== null && o.format !== null && o.format !== 'json') return { ok: false, message: '--root is for a JSON file.' };
142
+ return { ok: true, kind: 'file', o };
143
+ };
144
+
145
+ /** Brouillon d'une table distante sur fichier (POST /sources) : jamais de credential ni d'en-tête. Pure. */
146
+ const remoteDraft = (o, inspected, columns, key) => {
147
+ const format = o.format || inspected.format;
148
+ const csv = format === 'csv' ? { ...(inspected.csv || {}), ...(o.delimiter !== null ? { delimiter: o.delimiter === 'tab' ? '\\t' : o.delimiter } : {}), ...(o.header !== null ? { header: o.header } : {}), ...(o.encoding !== null ? { encoding: o.encoding.toLowerCase() } : {}) } : null;
149
+ const root = format === 'json' ? (o.root || inspected.root || null) : null;
150
+ return {
151
+ table: `public.${o.table}`,
152
+ ...(o.title ? { title: o.title } : {}),
153
+ mode: 'virtual',
154
+ origin: { kind: 'file', ...(o.storage ? { storage: o.storage } : { url: o.url }), format, ...(root ? { root } : {}), ...(csv && Object.keys(csv).length ? { csv } : {}) },
155
+ columns: columns.map((c) => ({ name: c.name, from: c.from, type: c.type, ...(c.transform ? { transform: c.transform } : {}) })),
156
+ ...(key && key.length ? { key } : {}),
157
+ };
158
+ };
159
+
160
+ /** Origine d'une table liée : hôte[:port]/base · schéma.table (jamais d'identifiant). Pure. */
161
+ const linkedOrigin = (o) => (o && o.host ? `${o.host}${o.port && o.port !== 5432 ? `:${o.port}` : ''}/${o.database || ''} · ${o.schema || 'public'}.${o.table || ''}` : '');
27
162
 
28
163
  // Engine 0.64.0 et plus : sources (/meta/v1/sources), déclarées dans poad/sources
29
164
  const supportsSources = (config) => {
@@ -56,6 +191,32 @@ const sourceLines = (s, width = 0) => {
56
191
  const more = (s.problems || []).length > 1 ? ` (+${s.problems.length - 1} more)` : '';
57
192
  return [chalk.redBright(` ✖ ${name} ${s.file}`), chalk.redBright(` ${first.line ? `line ${first.line}: ` : first.path ? `${first.path}: ` : ''}${first.message || 'invalid declaration'}${more}`)];
58
193
  }
194
+ if (s.mode === 'virtual' && (s.remote || (s.origin && s.origin.kind === 'file'))) {
195
+ // Table distante sur fichier : DuckDB relit le fichier à chaque requête ; branchée (user mapping posé) ou non
196
+ const attached = Boolean(s.remote && s.remote.attached) && s.table_exists !== false;
197
+ const where = (s.remote && s.remote.location) || remoteLocation(s.origin);
198
+ const format = (s.remote && s.remote.format) || (s.origin && s.origin.format) || '';
199
+ const facts = ['remote table (file)', s.table, [format, where].filter(Boolean).join(' '), attached ? 'attached' : 'not attached'].filter(Boolean).join(' ');
200
+ const out = [` ${attached && !(s.problems && s.problems.length) ? chalk.greenBright('✔') : chalk.yellowBright('!')} ${chalk.bold(name)} ${chalk.grey(facts)}`];
201
+ if (s.title && s.title !== s.name) out[0] += ` ${s.title}`;
202
+ for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
203
+ if (s.drift && s.drift.issues) for (const issue of s.drift.issues.slice(0, 5)) out.push(chalk.yellowBright(` table: ${typeof issue === 'string' ? issue : issue.message || JSON.stringify(issue)}`));
204
+ if (!attached) out.push(chalk.grey(` poad source test ${s.name} tells why`));
205
+ return out;
206
+ }
207
+ if (s.mode === 'virtual') {
208
+ // Table liée : rien n'est copié, pas d'exécution ; branchée (adresse vérifiée et user mapping posés) ou non
209
+ const attached = Boolean(s.linked && s.linked.attached) && s.table_exists !== false;
210
+ const state = attached ? `linked (${s.linked.address})` : 'not linked';
211
+ const facts = ['linked table', s.table, linkedOrigin(s.origin), state].filter(Boolean).join(' ');
212
+ const out = [` ${attached && !(s.problems && s.problems.length) ? chalk.greenBright('✔') : chalk.yellowBright('!')} ${chalk.bold(name)} ${chalk.grey(facts)}`];
213
+ if (s.title && s.title !== s.name) out[0] += ` ${s.title}`;
214
+ for (const p of s.problems || []) out.push(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
215
+ if (s.linked && s.linked.credential_problem) out.push(chalk.yellowBright(` credential: ${s.linked.credential_problem}`));
216
+ if (s.drift && s.drift.issues) for (const issue of s.drift.issues.slice(0, 5)) out.push(chalk.yellowBright(` table: ${typeof issue === 'string' ? issue : issue.message || JSON.stringify(issue)}`));
217
+ if (!attached) out.push(chalk.grey(` poad source test ${s.name} tells why`));
218
+ return out;
219
+ }
59
220
  const last = s.last_run;
60
221
  const failed = last && last.status === 'failed';
61
222
  const state = !last ? 'never run' : last.status === 'completed' ? `synced ${age(s.age_seconds)} ago` : last.status;
@@ -86,6 +247,7 @@ const reportLines = (r) => {
86
247
  ` ${count(r.received)} received, ${count(r.inserted)} added, ${count(r.updated)} updated, ${count(r.deleted)} removed, ${count(r.unchanged)} unchanged`,
87
248
  chalk.grey(` ${r.table || ''}: ${count(r.rows)} rows${r.forced ? ', deletion guard lifted (--force)' : ''}${typeof r.duration_ms === 'number' ? `, applied in ${flows.duration(r.duration_ms)}` : ''}`),
88
249
  ];
250
+ if (r.strategy === 'replace') out.push(chalk.grey(' full replacement (generated key without a natural key)'));
89
251
  if (typeof r.received === 'number' && typeof r.kept === 'number' && r.kept < r.received) out.push(chalk.yellowBright(` ${count(r.received - r.kept)} received row(s) left out (no key, or the same key twice)`));
90
252
  for (const p of Array.isArray(r.problems) ? r.problems : []) out.push(chalk.yellowBright(` ${p}`));
91
253
  return out;
@@ -176,8 +338,9 @@ const main = async (args = {}, raw, deps = {}) => {
176
338
  const error = data && typeof data === 'object' && data.error && typeof data.error === 'object' ? data.error : null;
177
339
  if (error && error.message) throw new SourceError(`${error.message}${error.hint ? ` (${error.hint})` : ''}`);
178
340
  // Fichier envoyé, échantillon, rapprochement : engine 0.65.0 ; le reste : 0.64.0
179
- const needs = /\/sources\/(uploads|sample|propose|preview|tables)\b/.test(route) ? '0.65.0' : '0.64.0';
180
- if (res.status === 404) throw new SourceError(`${t.cloud ? t.label : 'The engine'} has no ${needs === '0.65.0' ? 'such sources API' : 'sources API'} (HTTP 404): engine ${needs} or later is needed.`);
341
+ // Table distante sur fichier : engine 0.67.0 ; table liée : 0.66.0
342
+ const needs = /\/sources\/remote\b/.test(route) ? '0.67.0' : /\/sources\/linked\b/.test(route) ? '0.66.0' : /\/sources\/(uploads|sample|propose|preview|tables)\b/.test(route) ? '0.65.0' : '0.64.0';
343
+ if (res.status === 404) throw new SourceError(`${t.cloud ? t.label : 'The engine'} has no ${needs === '0.64.0' ? 'sources API' : 'such sources API'} (HTTP 404): engine ${needs} or later is needed.`);
181
344
  if (res.status === 401 || res.status === 403) throw new SourceError(t.cloud ? `${t.label} refused the access (HTTP ${res.status}): "poad login" again, or check that you own the project.` : `the engine refused the service_role key (HTTP ${res.status})`);
182
345
  throw new SourceError(`HTTP ${res.status}`);
183
346
  };
@@ -297,7 +460,7 @@ const main = async (args = {}, raw, deps = {}) => {
297
460
  // Nouvelle source : échantillon lu par l'engine, nouvelle table (ou --existing), déclaration écrite, chargement.
298
461
  // Source déjà envoyée (--name, ou le nom tiré du fichier) : nouvelle version au même chemin, puis chargement.
299
462
  if (command === 'import') {
300
- const opts = { file: null, name: null, table: null, key: null, format: null, root: null, existing: false, wait: true };
463
+ const opts = { file: null, name: null, table: null, key: null, generated: null, format: null, root: null, existing: false, wait: true, options: {} };
301
464
  const rest = words.slice(1);
302
465
  for (let i = 0; i < rest.length; i++) {
303
466
  const w = rest[i];
@@ -310,8 +473,24 @@ const main = async (args = {}, raw, deps = {}) => {
310
473
  if (w === '--name') opts.name = value();
311
474
  else if (w === '--table') opts.table = value().replace(/^public\./, '');
312
475
  else if (w === '--key') opts.key = value().split(',').map((x) => x.trim()).filter(Boolean);
476
+ else if (w === '--key-generated') opts.generated = value();
313
477
  else if (w === '--format') opts.format = value();
314
478
  else if (w === '--root') opts.root = value();
479
+ // Options du lecteur des formats lus par source-read 1.3.0 (bloc origin.<format> de la déclaration)
480
+ else if (w === '--sheet') {
481
+ const v = value();
482
+ opts.options.sheet = /^\d+$/.test(v) ? Number(v) : v;
483
+ } else if (w === '--header') {
484
+ const v = value();
485
+ if (v === 'none' || v === '0' || v === 'false') opts.options.header = false;
486
+ else if (/^[1-9]\d*$/.test(v)) opts.options.header = Number(v);
487
+ else throw new SourceError(`poad source import: --header takes a row number, or none (got "${v}").`);
488
+ } else if (w === '--records') opts.options.records = value();
489
+ else if (w === '--expand-until') {
490
+ const v = value();
491
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(v)) throw new SourceError(`poad source import: --expand-until takes a date, YYYY-MM-DD (got "${v}").`);
492
+ opts.options.expand = { until: v };
493
+ } else if (w === '--kinds') opts.options.kinds = value().split(',').map((x) => x.trim()).filter(Boolean);
315
494
  else if (w === '--existing') opts.existing = true;
316
495
  else if (w === '--detach' || w === '-d') opts.wait = false;
317
496
  else if (w.startsWith('-')) return fail(`poad source import: unknown option ${w}.`, 2);
@@ -321,12 +500,15 @@ const main = async (args = {}, raw, deps = {}) => {
321
500
  return fail(err.message, 2);
322
501
  }
323
502
  }
324
- const usage = 'Usage: poad source import <file> [--table <table>] [--name <source>] [--key <col,…>] [--existing] [--format csv|json|geojson|jsonl] [--root <path>] [--detach] [--env <name>]';
503
+ const usage =
504
+ 'Usage: poad source import <file> [--table <table>] [--name <source>] [--key <col,…> | --key-generated uuid|identity|hash] [--existing] [--format csv|json|geojson|jsonl|ics|xlsx|ods|xml|kml|kmz|gpx] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach] [--env <name>]';
325
505
  if (!opts.file) return fail(usage, 2);
326
506
  const file = path.resolve(cwd, opts.file);
327
507
  if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return fail(`${opts.file}: no such file.`);
328
- if (opts.format && !['csv', 'json', 'geojson', 'jsonl'].includes(opts.format)) return fail(`--format: csv, json, geojson or jsonl (got "${opts.format}").`, 2);
508
+ if (opts.format && !FORMATS.includes(opts.format)) return fail(`--format: ${FORMATS.join(', ')} (got "${opts.format}").`, 2);
329
509
  if (opts.existing && !opts.table) return fail('--existing needs --table <table> (the table of the project to load).', 2);
510
+ if (opts.generated && !['uuid', 'identity', 'hash'].includes(opts.generated)) return fail(`--key-generated: uuid, identity or hash (got "${opts.generated}").`, 2);
511
+ if (opts.generated && (opts.key || opts.existing)) return fail('--key-generated is for a new table without a natural key: not with --key nor --existing.', 2);
330
512
  const base = path.basename(file).replace(/\.gz$/i, '').replace(/\.[a-z0-9]+$/i, '');
331
513
  const { cleanIdent } = require('../utils/naming');
332
514
  // Nouvelle table : nom nettoyé (accents, espaces, chiffre en tête…) ; table existante : telle quelle
@@ -366,9 +548,13 @@ const main = async (args = {}, raw, deps = {}) => {
366
548
  // Nouvelle version : même chemin, la déclaration ne change pas
367
549
  started = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/refresh`, { force: false }));
368
550
  } else {
369
- const sample = await guard(() => call(t, 'POST', '/meta/v1/sources/sample', { path: target.path, ...(opts.format ? { format: opts.format } : {}), ...(opts.root ? { root: opts.root } : {}) }));
551
+ const options = Object.keys(opts.options).length ? { options: opts.options } : {};
552
+ const sample = await guard(() => call(t, 'POST', '/meta/v1/sources/sample', { path: target.path, ...(opts.format ? { format: opts.format } : {}), ...(opts.root ? { root: opts.root } : {}), ...options }));
370
553
  if (!sample) return;
371
554
  console.log(chalk.grey(` ${sample.format}${sample.gzip ? ' (gzip)' : ''}, ${(sample.fields || []).length} field(s): ${(sample.fields || []).map((f) => `${f.path} ${f.type}`).slice(0, 12).join(', ')}${(sample.fields || []).length > 12 ? '…' : ''}`));
555
+ // Formats lus par source-read : ce que le lecteur a choisi (feuille, ligne d'en-tête, enregistrements)
556
+ const found = describeReader(sample);
557
+ if (found) console.log(chalk.grey(` ${found}`));
372
558
  const proposal = await guard(() => call(t, 'POST', '/meta/v1/sources/propose', { fields: sample.fields, format: sample.format, path: target.path, table, ...(opts.existing ? { existing: true, name } : {}) }));
373
559
  if (!proposal) return;
374
560
  let columns;
@@ -383,10 +569,12 @@ const main = async (args = {}, raw, deps = {}) => {
383
569
  columns = (proposal.columns || []).filter((c) => c.include !== false).map((c) => ({ name: c.name, from: c.from, type: c.type, ...(c.transform ? { transform: c.transform } : {}) }));
384
570
  key = opts.key || proposal.key || [];
385
571
  }
386
- if (!key.length) return fail(`No key found for public.${table}: --key <column> (a column whose values are unique).`, 2);
572
+ // Clé générée par poad (nouvelle table sans clé naturelle) : colonne id ajoutée en tête
573
+ if (opts.generated) key = { generated: opts.generated };
574
+ else if (!key.length) return fail(`No key found for public.${table}: --key <column> (a column whose values are unique), or --key-generated uuid|identity|hash (an id column added by poad).`, 2);
387
575
  const draft = {
388
576
  mode: 'imported',
389
- origin: { kind: 'upload', path: target.path, format: sample.format, ...(sample.root ? { root: sample.root } : {}), ...(sample.format === 'csv' && sample.csv ? { csv: { delimiter: sample.csv.delimiter, ...(sample.csv.encoding ? { encoding: sample.csv.encoding } : {}) } } : {}) },
577
+ origin: { kind: 'upload', path: target.path, format: sample.format, ...(sample.root ? { root: sample.root } : {}), ...(sample.format === 'csv' && sample.csv ? { csv: { delimiter: sample.csv.delimiter, ...(sample.csv.encoding ? { encoding: sample.csv.encoding } : {}) } } : {}), ...(sample.options && Object.keys(sample.options).length ? { options: sample.options } : {}) },
390
578
  table: `public.${table}`,
391
579
  existing: opts.existing,
392
580
  key,
@@ -396,7 +584,9 @@ const main = async (args = {}, raw, deps = {}) => {
396
584
  if (!created) return;
397
585
  if (created.name) name = created.name;
398
586
  for (const w of created.warnings || []) console.log(chalk.yellowBright(` ${w}`));
399
- console.log(`${chalk.greenBright('✔')} source ${chalk.bold(name)} ${chalk.grey(`${created.file || 'created in the console'} → public.${table}, key ${key.join(', ')}`)}`);
587
+ const keyText = Array.isArray(key) ? `key ${key.join(', ')}` : `generated key ${key.generated}`;
588
+ console.log(`${chalk.greenBright('✔')} source ${chalk.bold(name)} ${chalk.grey(`${created.file || 'created in the console'} → public.${table}, ${keyText}`)}`);
589
+ if (opts.generated === 'uuid' || opts.generated === 'identity') console.log(chalk.grey(' No natural key: each new version replaces the whole table content (one transaction), under the deletion guard.'));
400
590
  started = created.run_id ? { run_id: created.run_id, flow: `source-${name.replace(/_/g, '-')}` } : null;
401
591
  if (!started) return fail('The source was declared but no load was started: poad source refresh ' + name + where);
402
592
  }
@@ -404,6 +594,108 @@ const main = async (args = {}, raw, deps = {}) => {
404
594
  return followRun(t, name, started, false, opts.wait);
405
595
  }
406
596
 
597
+ // ------------------------------------------------------------------ test
598
+ // Table liée : meta refait la garde des adresses, rebranche (adresse vérifiée, user mapping depuis le coffre) et lit une ligne
599
+ if (command === 'test') {
600
+ const name = words[1];
601
+ if (!name || words.length > 2) return fail('Usage: poad source test <name> [--env <name>] (a linked or remote table: "poad source ls" lists them).', 2);
602
+ if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name.`, 2);
603
+ const t = await ready();
604
+ if (!t) return;
605
+ const r = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/test`, {}));
606
+ if (!r) return;
607
+ if (json) return console.log(JSON.stringify(r, null, 2));
608
+ const ms = typeof r.duration_ms === 'number' ? ` (${Math.round(r.duration_ms)} ms)` : '';
609
+ if (r.location) {
610
+ // Table distante sur fichier : lue par Postgres (DuckDB), à l'emplacement rendu sans query string
611
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(`the remote file is readable${ms}, ${remoteLocation({ url: /^https?:/.test(r.location) ? r.location : null, storage: null }) || r.location}`)}`);
612
+ if (r.table) console.log(chalk.grey(` ${r.table}: read by Postgres, nothing copied${typeof r.sample_rows === 'number' ? `, ${r.sample_rows ? 'rows found' : 'no row'}` : ''}`));
613
+ return;
614
+ }
615
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(`the remote table answers${ms}${r.address ? `, checked address ${r.address}` : ''}`)}`);
616
+ return;
617
+ }
618
+
619
+ // ------------------------------------------------------------------ link
620
+ // Table liée : l'engine se connecte en lecture seule (garde des adresses internes), propose les colonnes de la table
621
+ // distante, puis écrit la déclaration (poad/sources/<table>.yaml) et la migration de la table étrangère. Le credential
622
+ // (utilisateur et mot de passe) est déjà dans le coffre : poad credential, ou l'écran Credentials ; jamais ici.
623
+ // Table distante sur fichier (engine 0.67.0) : l'engine vérifie l'adresse (garde des adresses internes) ou l'objet du
624
+ // Stockage, lit un échantillon et propose les colonnes ; puis la déclaration (poad/sources/<table>.yaml) et la
625
+ // migration de la table étrangère (duckdb_fdw) sont écrites. Rien n'est copié : chaque requête relit le fichier.
626
+ const linkFile = async (o) => {
627
+ const t = await ready();
628
+ if (!t) return;
629
+ const where = o.storage ? { storage: o.storage } : { url: o.url };
630
+ const csv = { ...(o.delimiter !== null ? { delimiter: o.delimiter === 'tab' ? '\\t' : o.delimiter } : {}), ...(o.header !== null ? { header: o.header } : {}), ...(o.encoding !== null ? { encoding: o.encoding.toLowerCase() } : {}) };
631
+ const seen = await guard(() => call(t, 'POST', '/meta/v1/sources/remote/inspect', { ...where, ...(o.format ? { format: o.format } : {}), ...(o.root ? { root: o.root } : {}), ...(Object.keys(csv).length ? { csv } : {}), name: o.table }));
632
+ if (!seen) return;
633
+ let columns = Array.isArray(seen.columns) ? seen.columns : [];
634
+ if (o.columns) {
635
+ const wanted = o.columns.split(',').map((x) => x.trim()).filter(Boolean);
636
+ const unknown = wanted.filter((w) => !columns.some((c) => c.from === w || c.name === w));
637
+ if (unknown.length) return fail(`The file has no field ${unknown.map((u) => `"${u}"`).join(', ')} (it has: ${columns.map((c) => c.from).join(', ')}).`);
638
+ columns = columns.filter((c) => wanted.includes(c.from) || wanted.includes(c.name));
639
+ }
640
+ if (!columns.length) return fail(`${remoteLocation(where)}: no column to read.`);
641
+ if (!o.format && !seen.format) return fail('The engine could not tell the format of the file: --format csv|json|jsonl|geojson|parquet.', 2);
642
+ const key = (seen.key || []).filter((k) => columns.some((c) => c.name === k));
643
+ const draft = remoteDraft(o, seen, columns, key);
644
+ if (!json) {
645
+ console.log(`${chalk.bold(o.table)} ${chalk.grey(`${draft.origin.format} ${remoteLocation(draft.origin)}${typeof seen.duration_ms === 'number' ? `, read in ${Math.round(seen.duration_ms)} ms` : ''}`)}`);
646
+ const w = Math.max(...columns.map((c) => c.name.length));
647
+ for (const c of columns) console.log(chalk.grey(` ${c.name.padEnd(w)} ${c.type}${c.from !== c.name ? ` ← ${c.from}` : ''}${c.transform ? ` (${c.transform})` : ''}`));
648
+ }
649
+ const saved = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft }));
650
+ if (!saved) return;
651
+ if (json) return console.log(JSON.stringify(saved, null, 2));
652
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(saved.name || o.table)} ${chalk.grey(`public.${o.table} → ${remoteLocation(draft.origin)}, ${columns.length} column${columns.length > 1 ? 's' : ''}, nothing copied`)}`);
653
+ if (saved.file) console.log(chalk.grey(` ${saved.file}${saved.report && saved.report.created && saved.report.created.migration ? `, ${saved.report.created.migration}` : ''}`));
654
+ for (const p of saved.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
655
+ console.log(chalk.grey(` Every query reads the file again. Private: never served by the API; read it in SQL, through a security_invoker view or a function. "poad source test ${saved.name || o.table}" checks it.`));
656
+ };
657
+
658
+ if (command === 'link') {
659
+ const parsed = parseLinkArgs(words.slice(1));
660
+ if (!parsed.ok) return fail(parsed.message, 2);
661
+ const o = parsed.o;
662
+ if (parsed.kind === 'file') return linkFile(o);
663
+ const port = o.port === null ? undefined : Number(o.port);
664
+ if (port !== undefined && !(Number.isInteger(port) && port >= 1 && port <= 65535)) return fail('--port: 1 to 65535.', 2);
665
+ const dot = o.remote.indexOf('.');
666
+ const remote = dot > 0 ? { schema: o.remote.slice(0, dot), table: o.remote.slice(dot + 1) } : { schema: 'public', table: o.remote };
667
+ const t = await ready();
668
+ if (!t) return;
669
+ const conn = { host: o.host, ...(port ? { port } : {}), database: o.database, credential: o.credential, sslmode: o.sslmode, name: o.table };
670
+ const seen = await guard(() => call(t, 'POST', '/meta/v1/sources/linked/inspect', { ...conn, ...remote }));
671
+ if (!seen) return;
672
+ let columns = Array.isArray(seen.columns) ? seen.columns : [];
673
+ if (o.columns) {
674
+ const wanted = o.columns.split(',').map((x) => x.trim()).filter(Boolean);
675
+ const unknown = wanted.filter((w) => !columns.some((c) => c.from === w || c.name === w));
676
+ if (unknown.length) return fail(`${remote.schema}.${remote.table} has no column ${unknown.map((u) => `"${u}"`).join(', ')} (it has: ${columns.map((c) => c.from).join(', ')}).`);
677
+ columns = columns.filter((c) => wanted.includes(c.from) || wanted.includes(c.name));
678
+ }
679
+ if (!columns.length) return fail(`${remote.schema}.${remote.table}: no column to link.`);
680
+ const key = (seen.key || []).filter((k) => columns.some((c) => c.name === k));
681
+ const draft = {
682
+ table: `public.${o.table}`,
683
+ ...(o.title ? { title: o.title } : {}),
684
+ mode: 'virtual',
685
+ origin: { kind: 'postgres', host: o.host, ...(port ? { port } : {}), database: o.database, schema: remote.schema, table: remote.table, credential: o.credential, sslmode: o.sslmode },
686
+ columns: columns.map((c) => ({ name: c.name, from: c.from, type: c.type })),
687
+ ...(key.length ? { key } : {}),
688
+ };
689
+ const saved = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft }));
690
+ if (!saved) return;
691
+ if (json) return console.log(JSON.stringify(saved, null, 2));
692
+ console.log(`${chalk.greenBright('✔')} ${chalk.bold(saved.name || o.table)} ${chalk.grey(`public.${o.table} → ${linkedOrigin(draft.origin)}, ${columns.length} column${columns.length > 1 ? 's' : ''}, nothing copied`)}`);
693
+ if (saved.file) console.log(chalk.grey(` ${saved.file}${saved.report && saved.report.created && saved.report.created.migration ? `, ${saved.report.created.migration}` : ''}`));
694
+ for (const p of saved.problems || []) console.log(chalk.yellowBright(` ${p.path ? `${p.path}: ` : ''}${p.message}`));
695
+ console.log(chalk.grey(` Private: never served by the API. Read it in SQL, through a security_invoker view or a function. "poad source test ${saved.name || o.table}" checks it.`));
696
+ return;
697
+ }
698
+
407
699
  // ------------------------------------------------------------------ pull
408
700
  // La déclaration d'une source (créée dans la console hébergée, gardée en base) écrite dans poad/sources :
409
701
  // le fichier fait foi ensuite (poad deploy l'envoie ; sur poad.io, un fichier déployé l'emporte).
@@ -441,4 +733,4 @@ const main = async (args = {}, raw, deps = {}) => {
441
733
  };
442
734
 
443
735
  module.exports = (args, raw) => main(args, raw);
444
- Object.assign(module.exports, { main, supportsSources, sourceLines, reportOf, reportLines, guardRefused, age, NAME_RE });
736
+ Object.assign(module.exports, { main, supportsSources, sourceLines, reportOf, reportLines, guardRefused, age, linkedOrigin, remoteLocation, parseStorageRef, parseLinkArgs, remoteDraft, REMOTE_FORMATS, NAME_RE, FORMATS, describeReader });
@@ -143,6 +143,16 @@ module.exports = async (args = {}) => {
143
143
  process.exitCode = 1;
144
144
  return;
145
145
  }
146
+ // Ce que l'API de la nouvelle version ne servira plus à anon ni à authenticated (lu dans la base, si elle tourne)
147
+ if (await isDockerExist(config.project_uuid)) {
148
+ const exposure = require('../utils/api-exposure');
149
+ const found = exposure.readLocal(config.project_uuid);
150
+ if (found) {
151
+ const lines = exposure.lines(exposure.impact({ current, target, items: found.items }), chalk);
152
+ for (const l of lines) console.log(l);
153
+ if (lines.length) console.log(' ');
154
+ }
155
+ }
146
156
  if (!(await confirm(`Upgrade to engine ${target}?`))) return;
147
157
  const running = await stopProject();
148
158
  await startProject(running, { upgrade: true, allowMinor: true, target });
@@ -0,0 +1,60 @@
1
+ // Ce que l'API ne sert pas à anon ni à authenticated (SECURITY DEFINER, vues sans security_invoker, vues
2
+ // matérialisées) : poad deploy (réponse de poad.io) et poad upgrade (base locale)
3
+ const test = require('node:test');
4
+ const assert = require('node:assert/strict');
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const exposure = require('../utils/api-exposure');
8
+ const { summarize } = require('../project/deploy');
9
+
10
+ const chalk = new Proxy({}, { get: () => new Proxy((s) => s, { get: (_, __) => (s) => s }) });
11
+ const definer = { kind: 'function', schema: 'public', name: 'est_admin', signature: 'est_admin(uuid)', reason: 'security_definer', anon: true, authenticated: true };
12
+ const view = { kind: 'view', schema: 'public', name: 'stats', reason: 'view_owner_rights', anon: false, authenticated: true };
13
+
14
+ test('phases : servies avant 0.64.0, refusées à tous jusqu’à 0.65.x, service_role seulement depuis 0.66.0', () => {
15
+ assert.equal(exposure.phaseOf('0.62.0'), 'served');
16
+ assert.equal(exposure.phaseOf('0.64.0'), 'refused_all');
17
+ assert.equal(exposure.phaseOf('0.65.9'), 'refused_all');
18
+ assert.equal(exposure.phaseOf('0.66.0'), 'service_role_only');
19
+ assert.equal(exposure.phaseOf('?'), null);
20
+ assert.equal(exposure.phaseOf('0.66.0-rpc'), 'service_role_only');
21
+ assert.equal(exposure.impact({ current: '0.65.0', target: '0.66.0-rpc', items: [definer] }).change, 'regained_service_role');
22
+ });
23
+
24
+ test('poad upgrade 0.62 → 0.66 : perdues pour anon et authenticated, correctif par objet', () => {
25
+ const x = exposure.impact({ current: '0.62.0', target: '0.66.0', items: [definer, view] });
26
+ assert.equal(x.change, 'lost');
27
+ assert.deepEqual(x.items[1].roles, ['authenticated']);
28
+ assert.equal(x.items[1].fix, 'alter view public.stats set (security_invoker = true);');
29
+ const out = exposure.lines(x, chalk).join('\n');
30
+ assert.match(out, /With engine 0\.66\.0, the API no longer serves 2 function\(s\) or view\(s\) to anon or authenticated/);
31
+ assert.match(out, /alter function est_admin\(uuid\) security invoker;/);
32
+ assert.match(out, /public\.stats .*authenticated/);
33
+ });
34
+
35
+ test('0.65 → 0.66 : rien de perdu, service_role les reçoit de nouveau ; rien à dire sans objet', () => {
36
+ assert.equal(exposure.impact({ current: '0.65.0', target: '0.66.0', items: [definer] }).change, 'regained_service_role');
37
+ assert.deepEqual(exposure.lines(exposure.impact({ current: '0.62.0', target: '0.66.0', items: [] }), chalk), []);
38
+ });
39
+
40
+ test('poad deploy : l’avertissement de poad.io relu, décision du serveur gardée, objets des migrations en attente', () => {
41
+ const r = summarize({
42
+ outcome: 'success',
43
+ dry_run: true,
44
+ api_exposure: { current: '0.66.0', target: '0.66.0', change: 'unchanged', items: [{ kind: 'function', schema: 'public', name: 'nouvelle', reason: 'security_definer', roles: ['anon', 'authenticated'], source: 'pending_migration', file: '20261202000000_x.sql' }] },
45
+ });
46
+ assert.equal(r.api_exposure.change, 'unchanged');
47
+ assert.equal(r.api_exposure.count, 1);
48
+ const out = exposure.lines(r.api_exposure, chalk).join('\n');
49
+ assert.match(out, /refused to anon and authenticated/);
50
+ assert.match(out, /created by 20261202000000_x\.sql/);
51
+ assert.equal(summarize({ outcome: 'success' }).api_exposure, null);
52
+ });
53
+
54
+ test('la requête est la même que celle de poad.io (api-exposure.sql)', () => {
55
+ const sql = fs.readFileSync(path.join(__dirname, '../utils/api-exposure/api-exposure.sql'), 'utf8');
56
+ assert.match(sql, /set default_transaction_read_only = on/);
57
+ assert.match(sql, /p\.prosecdef/);
58
+ assert.match(sql, /security_invoker=true/);
59
+ assert.match(sql, /c\.relkind = 'm'/);
60
+ });
@@ -208,3 +208,19 @@ test('poad source import --name : nouvelle version d’une source envoyée (mêm
208
208
  assert.ok(state.requests.some((q) => q.path === '/meta/v1/sources/communes/refresh'));
209
209
  assert.ok(!state.requests.some((q) => q.path === '/meta/v1/sources/sample'));
210
210
  });
211
+
212
+ test('poad source import --key-generated : clé générée (sans clé naturelle), refus des combinaisons', async (t) => {
213
+ const { base, state } = await fakeEngine(t, { tus: true });
214
+ const file = path.join(tmpdir(t), 'films.csv');
215
+ fs.writeFileSync(file, ',Title\n0,A\n1,A\n');
216
+ const { out, exit } = await capture(() => source.main({}, ['import', file, '--key-generated', 'hash', '--project', 'p1'], cloudDeps(base)));
217
+ assert.strictEqual(exit, 0, out);
218
+ assert.deepStrictEqual(state.draft.key, { generated: 'hash' });
219
+ assert.match(out, /generated key hash/);
220
+ const bad = await capture(() => source.main({}, ['import', file, '--key-generated', 'random', '--project', 'p1'], cloudDeps(base)));
221
+ assert.strictEqual(bad.exit, 2);
222
+ assert.match(bad.out, /--key-generated: uuid, identity or hash/);
223
+ const both = await capture(() => source.main({}, ['import', file, '--key-generated', 'uuid', '--key', 'Title', '--project', 'p1'], cloudDeps(base)));
224
+ assert.strictEqual(both.exit, 2);
225
+ assert.match(both.out, /not with --key nor --existing/);
226
+ });
@@ -57,6 +57,18 @@ function fakeCloud(t, behaviour = {}) {
57
57
  if (req.method === 'POST' && url.pathname === '/meta/v1/sources/communes/refresh') return send(res, 202, { source: 'communes', flow: 'source-communes', run_id: RUN, force: body && body.force === true, drift: { issues: [], sql: [] } });
58
58
  if (req.method === 'GET' && url.pathname === '/meta/v1/sources/communes-ref/yaml') return send(res, 200, { name: 'communes-ref', stored: 'console', file: 'poad/sources/communes-ref.yaml', yaml: YAML });
59
59
  if (req.method === 'GET' && url.pathname === '/meta/v1/sources/absente/yaml') return send(res, 404, { error: { code: 'not_found', message: 'source inconnue : absente' } });
60
+ if (req.method === 'POST' && url.pathname === '/meta/v1/sources/linked/inspect') {
61
+ if (body.host === '10.0.0.5') return send(res, 400, { error: { code: 'internal_address', message: 'adresse interne refusée (10.0.0.5) : une table liée lit une base sur internet' } });
62
+ return send(res, 200, { ok: true, schema: body.schema, table: body.table, key: ['id'], columns: [{ name: 'id', from: 'id', type: 'integer' }, { name: 'nom_client', from: 'Nom Client', type: 'text' }, { name: 'ville', from: 'ville', type: 'character varying(60)' }] });
63
+ }
64
+ if (req.method === 'POST' && url.pathname === '/meta/v1/sources/remote/inspect') {
65
+ if (body.url && body.url.includes('127.0.0.1')) return send(res, 400, { error: { code: 'internal_address', message: 'adresse interne refusée (127.0.0.1) : une table distante lit un fichier sur internet' } });
66
+ const csv = body.storage || (body.format === 'csv');
67
+ return send(res, 200, { ok: true, location: body.storage ? `storage://${body.storage.bucket}/${body.storage.path}` : 'https://data.example.org/arrets.geojson', format: csv ? 'csv' : 'geojson', ...(csv ? { csv: { delimiter: ';', header: true } } : {}), duration_ms: 41, key: [], columns: csv ? [{ name: 'code', from: 'Code', type: 'text' }, { name: 'population', from: 'Population', type: 'integer' }] : [{ name: 'id', from: 'id', type: 'text' }, { name: 'nom', from: 'nom', type: 'text' }, { name: 'geometry', from: 'geometry', type: 'geometry(Point,4326)', transform: 'geojson' }] });
68
+ }
69
+ if (req.method === 'POST' && url.pathname === '/meta/v1/sources/arrets_bus/test') return send(res, 200, { ok: true, source: 'arrets_bus', table: 'public.arrets_bus', readable: true, sample_rows: 1, duration_ms: 87, location: 'https://data.example.org/arrets.geojson?jeton=x' });
70
+ if (req.method === 'POST' && url.pathname === '/meta/v1/sources') return send(res, 201, { name: body.draft.origin.kind === 'file' ? body.draft.table.slice(7) : 'clients', stored: 'file', file: 'poad/sources/clients.yaml', table: 'public.clients', mode: 'virtual', problems: [], report: { created: { migration: 'poad/migrations/20261202000000_source_clients_liee.sql' } } });
71
+ if (req.method === 'POST' && url.pathname === '/meta/v1/sources/clients/test') return send(res, 200, { ok: true, source: 'clients', readable: true, duration_ms: 12 });
60
72
  if (req.method === 'POST' && url.pathname === '/meta/v1/sources/inconnue/refresh') return send(res, 404, { error: { code: 'not_found', message: 'source inconnue : inconnue', hint: 'déclarez-la dans poad/sources/inconnue.yaml' } });
61
73
  if (req.method === 'GET' && url.pathname === `/flows/v1/runs/${RUN}`) {
62
74
  state.polls++;
@@ -280,3 +292,153 @@ test('poad deploy : poad/sources est dans l’archive', (t) => {
280
292
  assert.ok(files.some((f) => f.path === 'sources/communes.yaml'), JSON.stringify(files));
281
293
  assert.ok(zlib.gunzipSync(bundle.build(dir).tgz).includes(Buffer.from('sources/communes.yaml')));
282
294
  });
295
+
296
+ // --- Tables liées (mode virtual, engine 0.66.0) -----------------------------------------
297
+
298
+ test('source link --env : colonnes proposées par l’engine, brouillon sans secret, puis source test', async (t) => {
299
+ const cloud = await fakeCloud(t);
300
+ const box = sandbox(t);
301
+ const r = await poad(box, cloud.api, ['source', 'link', 'clients', '--host', 'db.example.com', '--database', 'crm', '--remote', 'ventes.Clients', '--credential', 'crm-lecture', '--columns', 'id,Nom Client', '--env', 'dev']);
302
+ noSecret(r);
303
+ assert.strictEqual(r.status, 0, r.all);
304
+ const inspect = cloud.state.requests.find((q) => q.path === '/meta/v1/sources/linked/inspect').body;
305
+ assert.deepStrictEqual(inspect, { host: 'db.example.com', database: 'crm', credential: 'crm-lecture', sslmode: 'require', name: 'clients', schema: 'ventes', table: 'Clients' });
306
+ const draft = cloud.state.requests.find((q) => q.path === '/meta/v1/sources' && q.method === 'POST').body.draft;
307
+ assert.deepStrictEqual(draft, {
308
+ table: 'public.clients',
309
+ mode: 'virtual',
310
+ origin: { kind: 'postgres', host: 'db.example.com', database: 'crm', schema: 'ventes', table: 'Clients', credential: 'crm-lecture', sslmode: 'require' },
311
+ columns: [{ name: 'id', from: 'id', type: 'integer' }, { name: 'nom_client', from: 'Nom Client', type: 'text' }],
312
+ key: ['id'],
313
+ });
314
+ assert.match(r.stdout, /✔ clients {2}public\.clients → db\.example\.com\/crm · ventes\.Clients, 2 columns, nothing copied/);
315
+ assert.match(r.stdout, /never served by the API/);
316
+ const tst = await poad(box, cloud.api, ['source', 'test', 'clients', '--env', 'dev']);
317
+ assert.strictEqual(tst.status, 0, tst.all);
318
+ assert.match(tst.stdout, /✔ clients {2}the remote table answers \(12 ms\)/);
319
+ });
320
+
321
+ test('source link : adresse interne refusée par l’engine, colonne inconnue, usage', async (t) => {
322
+ const cloud = await fakeCloud(t);
323
+ const box = sandbox(t);
324
+ const r = await poad(box, cloud.api, ['source', 'link', 'clients', '--host', '10.0.0.5', '--database', 'crm', '--remote', 'Clients', '--credential', 'c', '--env', 'dev']);
325
+ assert.strictEqual(r.status, 1, r.all);
326
+ assert.match(r.stdout, /adresse interne refusée \(10\.0\.0\.5\)/);
327
+ assert.ok(!cloud.state.requests.some((q) => q.path === '/meta/v1/sources' && q.method === 'POST'), 'nothing declared');
328
+ const col = await poad(box, cloud.api, ['source', 'link', 'clients', '--host', 'db.example.com', '--database', 'crm', '--remote', 'Clients', '--credential', 'c', '--columns', 'absente', '--env', 'dev']);
329
+ assert.strictEqual(col.status, 1, col.all);
330
+ assert.match(col.stdout, /has no column "absente"/);
331
+ for (const args of [['source', 'link', 'clients'], ['source', 'link', 'clients', '--host', 'h', '--database', 'd', '--remote', 'r', '--credential', 'c', '--sslmode', 'prefer'], ['source', 'test']]) {
332
+ const u = await poad(box, cloud.api, args);
333
+ assert.strictEqual(u.status, 2, u.all);
334
+ }
335
+ });
336
+
337
+ test('sourceLines : table liée branchée ou non, origine sans identifiant', () => {
338
+ const s = { name: 'clients', valid: true, mode: 'virtual', table: 'public.clients', table_exists: true, origin: { kind: 'postgres', host: 'db.example.com', port: 6543, database: 'crm', schema: 'ventes', table: 'Clients', credential: 'crm-lecture' }, linked: { attached: true, address: '203.0.113.7', credential_problem: null }, problems: [] };
339
+ const strip = (lines) => lines.join('\n').replace(/\u001b\[[0-9;]*m/g, '');
340
+ assert.match(strip(source.sourceLines(s)), /✔ clients {2}linked table {2}public\.clients {2}db\.example\.com:6543\/crm · ventes\.Clients {2}linked \(203\.0\.113\.7\)/);
341
+ const off = strip(source.sourceLines({ ...s, linked: { attached: false, address: null, credential_problem: 'credential crm-lecture absent du coffre' } }));
342
+ assert.match(off, /! clients .*not linked/);
343
+ assert.match(off, /credential: credential crm-lecture absent du coffre/);
344
+ assert.match(off, /poad source test clients tells why/);
345
+ });
346
+
347
+ test('source import : formats lus par source-read et options du lecteur, refus clairs avant tout envoi', async (t) => {
348
+ const cloud = await fakeCloud(t);
349
+ const box = sandbox(t);
350
+ fs.writeFileSync(path.join(box.app, 'mesures.xlsx'), 'PK');
351
+ const badFormat = await poad(box, cloud.api, ['source', 'import', 'mesures.xlsx', '--format', 'parquet']);
352
+ assert.strictEqual(badFormat.status, 2, badFormat.all);
353
+ assert.match(badFormat.all, /--format: csv, json, geojson, jsonl, ics, xlsx, ods, xml, kml, kmz, gpx \(got "parquet"\)/);
354
+ const badHeader = await poad(box, cloud.api, ['source', 'import', 'mesures.xlsx', '--header', 'deux']);
355
+ assert.strictEqual(badHeader.status, 2, badHeader.all);
356
+ assert.match(badHeader.all, /--header takes a row number, or none/);
357
+ const badUntil = await poad(box, cloud.api, ['source', 'import', 'agenda.ics', '--expand-until', '31/12/2027']);
358
+ assert.strictEqual(badUntil.status, 2, badUntil.all);
359
+ assert.match(badUntil.all, /--expand-until takes a date, YYYY-MM-DD/);
360
+ });
361
+
362
+ test('describeReader : feuille, en-tête, enregistrements, répétitions, exécution', () => {
363
+ assert.strictEqual(source.describeReader({ details: { sheets: ['A', 'Mesures'], sheet: 'Mesures', header_row: 3 }, options: { sheet: 'Mesures', header: 3 }, run_id: 'r1' }), 'sheet "Mesures" (of "A", "Mesures"; --sheet), header on row 3, read by source-read (run r1)');
364
+ assert.strictEqual(source.describeReader({ details: { events: 9 }, options: { expand: { until: '2027-12-31' } } }), 'recurrences expanded until 2027-12-31, 9 event(s)');
365
+ assert.strictEqual(source.describeReader({ format: 'csv', csv: { delimiter: ';' } }), null);
366
+ assert.deepStrictEqual(source.FORMATS, ['csv', 'json', 'geojson', 'jsonl', 'ics', 'xlsx', 'ods', 'xml', 'kml', 'kmz', 'gpx']);
367
+ });
368
+
369
+ // --- Tables distantes sur fichier (mode virtual, engine 0.67.0) ---------------------------
370
+
371
+ test('source link --url : colonnes proposées par l’engine, brouillon fichier sans secret, puis source test', async (t) => {
372
+ const cloud = await fakeCloud(t);
373
+ const box = sandbox(t);
374
+ const r = await poad(box, cloud.api, ['source', 'link', 'arrets_bus', '--url', 'https://data.example.org/arrets.geojson?annee=2026', '--columns', 'nom,geometry', '--env', 'dev']);
375
+ noSecret(r);
376
+ assert.strictEqual(r.status, 0, r.all);
377
+ const inspect = cloud.state.requests.find((q) => q.path === '/meta/v1/sources/remote/inspect').body;
378
+ assert.deepStrictEqual(inspect, { url: 'https://data.example.org/arrets.geojson?annee=2026', name: 'arrets_bus' });
379
+ const draft = cloud.state.requests.find((q) => q.path === '/meta/v1/sources' && q.method === 'POST').body.draft;
380
+ assert.deepStrictEqual(draft, {
381
+ table: 'public.arrets_bus',
382
+ mode: 'virtual',
383
+ origin: { kind: 'file', url: 'https://data.example.org/arrets.geojson?annee=2026', format: 'geojson' },
384
+ columns: [{ name: 'nom', from: 'nom', type: 'text' }, { name: 'geometry', from: 'geometry', type: 'geometry(Point,4326)', transform: 'geojson' }],
385
+ });
386
+ assert.match(r.stdout, /geometry {2}geometry\(Point,4326\) {2}\(geojson\)/);
387
+ assert.match(r.stdout, /✔ arrets_bus {2}public\.arrets_bus → https:\/\/data\.example\.org\/arrets\.geojson, 2 columns, nothing copied/);
388
+ assert.ok(!r.stdout.includes('annee=2026 '), 'location printed without its query string');
389
+ const tst = await poad(box, cloud.api, ['source', 'test', 'arrets_bus', '--env', 'dev']);
390
+ assert.strictEqual(tst.status, 0, tst.all);
391
+ assert.match(tst.stdout, /✔ arrets_bus {2}the remote file is readable \(87 ms\), https:\/\/data\.example\.org\/arrets\.geojson\n/);
392
+ assert.ok(!tst.stdout.includes('jeton'), 'no query string');
393
+ });
394
+
395
+ test('source link --storage : objet du Stockage, options CSV, adresse interne refusée, options mêlées', async (t) => {
396
+ const cloud = await fakeCloud(t);
397
+ const box = sandbox(t);
398
+ const r = await poad(box, cloud.api, ['source', 'link', 'communes', '--storage', 'donnees/ref/communes.csv', '--delimiter', ';', '--encoding', 'Latin-1', '--env', 'dev']);
399
+ assert.strictEqual(r.status, 0, r.all);
400
+ const inspect = cloud.state.requests.find((q) => q.path === '/meta/v1/sources/remote/inspect').body;
401
+ assert.deepStrictEqual(inspect, { storage: { bucket: 'donnees', path: 'ref/communes.csv' }, csv: { delimiter: ';', encoding: 'latin-1' }, name: 'communes' });
402
+ const draft = cloud.state.requests.find((q) => q.path === '/meta/v1/sources' && q.method === 'POST').body.draft;
403
+ assert.deepStrictEqual(draft.origin, { kind: 'file', storage: { bucket: 'donnees', path: 'ref/communes.csv' }, format: 'csv', csv: { delimiter: ';', header: true, encoding: 'latin-1' } });
404
+ assert.match(r.stdout, /public\.communes → storage:\/\/donnees\/ref\/communes\.csv, 2 columns/);
405
+ const refused = await poad(box, cloud.api, ['source', 'link', 'interne', '--url', 'http://127.0.0.1:8000/x.csv', '--env', 'dev']);
406
+ assert.strictEqual(refused.status, 1, refused.all);
407
+ assert.match(refused.stdout, /adresse interne refusée \(127\.0\.0\.1\)/);
408
+ assert.strictEqual(cloud.state.requests.filter((q) => q.path === '/meta/v1/sources' && q.method === 'POST').length, 1, 'nothing more declared');
409
+ for (const args of [['source', 'link', 'x', '--url', 'https://a.org/f.csv', '--host', 'h'], ['source', 'link', 'x', '--storage', 'sansChemin'], ['source', 'link', 'x', '--url', 'ftp://a.org/f.csv'], ['source', 'link', 'x', '--url', 'https://a.org/f', '--format', 'xlsx']]) {
410
+ const u = await poad(box, cloud.api, [...args, '--env', 'dev']);
411
+ assert.strictEqual(u.status, 2, `${args.join(' ')}: ${u.all}`);
412
+ }
413
+ });
414
+
415
+ test('parseLinkArgs, parseStorageRef, remoteLocation, remoteDraft : formes et refus', () => {
416
+ const ok = source.parseLinkArgs(['t', '--url', 'https://a.org/f.json', '--format', 'json', '--root', 'data.items']);
417
+ assert.strictEqual(ok.kind, 'file');
418
+ assert.strictEqual(source.parseLinkArgs(['t', '--host', 'h', '--database', 'd', '--remote', 'r', '--credential', 'c']).kind, 'postgres');
419
+ assert.match(source.parseLinkArgs(['t', '--url', 'https://a.org/f.json', '--storage', 'b/p']).message, /not both/);
420
+ assert.match(source.parseLinkArgs(['t', '--url', 'https://u:p@a.org/f.csv']).message, /no user or password/);
421
+ assert.match(source.parseLinkArgs(['t', '--url', 'https://a.org/f.csv', '--format', 'geojson', '--delimiter', ';']).message, /for a CSV file/);
422
+ assert.match(source.parseLinkArgs(['t', '--url', 'https://a.org/f.csv', '--encoding', 'koi8-r']).message, /--encoding/);
423
+ assert.match(source.parseLinkArgs(['t', '--format', 'csv', '--host', 'h']).message, /for a file/);
424
+ assert.deepStrictEqual(source.parseStorageRef('storage://donnees/a/b.csv'), { bucket: 'donnees', path: 'a/b.csv' });
425
+ assert.match(source.parseStorageRef('donnees/../x'), /not an object path/);
426
+ assert.match(source.parseStorageRef('Donnees/x'), /not a bucket name/);
427
+ assert.strictEqual(source.remoteLocation({ url: 'https://a.org/f.csv?token=abc#x' }), 'https://a.org/f.csv');
428
+ assert.strictEqual(source.remoteLocation({ storage: { bucket: 'b', path: 'p/q.json' } }), 'storage://b/p/q.json');
429
+ const d = source.remoteDraft(ok.o, { format: 'json', root: 'ignored' }, [{ name: 'a', from: 'a', type: 'text' }], []);
430
+ assert.deepStrictEqual(d, { table: 'public.t', mode: 'virtual', origin: { kind: 'file', url: 'https://a.org/f.json', format: 'json', root: 'data.items' }, columns: [{ name: 'a', from: 'a', type: 'text' }] });
431
+ const tab = source.parseLinkArgs(['t', '--storage', 'b/f.tsv', '--delimiter', 'tab', '--no-header']);
432
+ assert.deepStrictEqual(source.remoteDraft(tab.o, { format: 'csv' }, [{ name: 'c', from: '#1', type: 'text' }], []).origin.csv, { delimiter: '\\t', header: false });
433
+ assert.deepStrictEqual(source.REMOTE_FORMATS, ['csv', 'json', 'jsonl', 'geojson', 'parquet']);
434
+ });
435
+
436
+ test('sourceLines : table distante sur fichier branchée ou non, emplacement sans query string', () => {
437
+ const s = { name: 'arrets_bus', valid: true, mode: 'virtual', table: 'public.arrets_bus', table_exists: true, origin: { kind: 'file', url: 'https://data.example.org/arrets.geojson?cle=1', storage: null, format: 'geojson' }, remote: { server: 'poad_remote_0123456789ab', attached: true, location: 'https://data.example.org/arrets.geojson', format: 'geojson' }, problems: [] };
438
+ const strip = (lines) => lines.join('\n').replace(/\u001b\[[0-9;]*m/g, '');
439
+ assert.match(strip(source.sourceLines(s)), /✔ arrets_bus {2}remote table \(file\) {2}public\.arrets_bus {2}geojson https:\/\/data\.example\.org\/arrets\.geojson {2}attached/);
440
+ const off = strip(source.sourceLines({ ...s, remote: null, origin: { kind: 'file', url: null, storage: { bucket: 'donnees', path: 'a.csv' }, format: 'csv' }, problems: [{ path: 'origin.url', message: 'adresse interne refusée' }] }));
441
+ assert.match(off, /! arrets_bus {2}remote table \(file\) {2}public\.arrets_bus {2}csv storage:\/\/donnees\/a\.csv {2}not attached/);
442
+ assert.match(off, /poad source test arrets_bus tells why/);
443
+ assert.ok(!off.includes('cle=1'));
444
+ });
@@ -0,0 +1,42 @@
1
+ -- Ce que l'API de l'engine ne sert pas à anon ni à authenticated, parce qu'il leur ferait contourner le RLS
2
+ -- (service data 0.10.0, engine 0.64.0 ; servi à service_role depuis data 0.12.0, engine 0.66.0) : fonctions
3
+ -- SECURITY DEFINER, vues sans security_invoker = true, vues matérialisées des schémas exposés. Seuls ceux que anon
4
+ -- ou authenticated atteignent comptent (droit EXECUTE, ou SELECT / INSERT : l'interrupteur « API ») : ce sont
5
+ -- ceux qu'un front perd. Mêmes règles que services/data/src/schema.ts de l'engine (triggers, membres
6
+ -- d'extensions et fonctions à arguments OUT / INOUT / VARIADIC ne sont jamais servis : exclus).
7
+ --
8
+ -- Lecture seule, une ligne JSON. Lu ici plutôt que demandé au service data : la base d'un engine plus ancien que
9
+ -- 0.66.0 (celui qu'on s'apprête à mettre à jour) n'a pas de route pour le dire.
10
+ -- psql -v schemas=public,autre -f api-exposure.sql (poad upgrade ; même requête que poad-site deploy/cloud/api-exposure.sql)
11
+ set default_transaction_read_only = on;
12
+ \set ON_ERROR_STOP 1
13
+ select json_build_object(
14
+ 'schemas', to_json(s.names),
15
+ 'items', coalesce((select json_agg(i order by i.kind, i.schema, i.name) from (
16
+ select 'function' as kind, n.nspname as schema, p.proname as name, p.oid::regprocedure::text as signature,
17
+ 'security_definer' as reason,
18
+ has_function_privilege('anon', p.oid, 'execute') as anon,
19
+ has_function_privilege('authenticated', p.oid, 'execute') as authenticated
20
+ from pg_proc p join pg_namespace n on n.oid = p.pronamespace
21
+ where n.nspname = any (s.names) and p.prokind = 'f' and p.prosecdef
22
+ and p.prorettype not in ('trigger'::regtype, 'event_trigger'::regtype)
23
+ and not exists (select 1 from pg_depend d where d.objid = p.oid and d.deptype = 'e')
24
+ and not coalesce(p.proargmodes::text[] && array['o', 'b', 'v'], false)
25
+ -- une surcharge INVOKER du même nom est servie à sa place : rien n'est perdu
26
+ and not exists (select 1 from pg_proc o where o.pronamespace = p.pronamespace and o.proname = p.proname and not o.prosecdef and o.prokind = 'f')
27
+ and (has_function_privilege('anon', p.oid, 'execute') or has_function_privilege('authenticated', p.oid, 'execute'))
28
+ union all
29
+ select case c.relkind when 'm' then 'materialized_view' else 'view' end, n.nspname, c.relname, null,
30
+ case c.relkind when 'm' then 'materialized_view' else 'view_owner_rights' end,
31
+ has_table_privilege('anon', c.oid, 'select') or has_table_privilege('anon', c.oid, 'insert'),
32
+ has_table_privilege('authenticated', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'insert')
33
+ from pg_class c join pg_namespace n on n.oid = c.relnamespace
34
+ where n.nspname = any (s.names)
35
+ and (c.relkind = 'm' or (c.relkind = 'v' and not coalesce((select bool_or(lower(o) in ('security_invoker=true', 'security_invoker=on', 'security_invoker=yes', 'security_invoker=1')) from unnest(c.reloptions) o), false)))
36
+ and not exists (select 1 from pg_depend d where d.classid = 'pg_class'::regclass and d.objid = c.oid and d.deptype = 'e')
37
+ and (has_table_privilege('anon', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'select')
38
+ or has_table_privilege('anon', c.oid, 'insert') or has_table_privilege('authenticated', c.oid, 'insert'))
39
+ ) i), '[]'::json)
40
+ )::jsonb::text -- une seule ligne (json_agg en met une par élément)
41
+ from (select array(select x from unnest(string_to_array(:'schemas', ',')) x
42
+ where x <> '' and x not in ('auth', 'storage', 'private', 'pg_catalog', 'information_schema')) as names) s;
@@ -0,0 +1,97 @@
1
+ // Fonctions et vues qu'un front (clés anon / authenticated) ne reçoit pas par l'API de l'engine : SECURITY
2
+ // DEFINER, vues sans security_invoker, vues matérialisées. Elles lui feraient contourner le RLS.
3
+ // - engine avant 0.64.0 : servies à tout rôle qui a le droit ;
4
+ // - 0.64.0 à 0.65.x : refusées à tous les rôles (403 not_exposed) ;
5
+ // - 0.66.0 et plus : refusées à anon et authenticated, servies à service_role (qui contourne déjà le RLS).
6
+ // Même règle que poad.io (poad-site deploy/cloud/control/api-exposure.mjs) : poad deploy reçoit la liste du serveur,
7
+ // poad upgrade la lit dans la base locale (api-exposure.sql) avant de proposer la mise à jour.
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { spawnSync } = require('child_process');
11
+
12
+ const HIDDEN_SINCE = '0.64.0';
13
+ const SERVICE_ROLE_SINCE = '0.66.0';
14
+ const SEMVER = /^(\d+)\.(\d+)\.(\d+)$/;
15
+ const cmp = (a, b) => {
16
+ const x = SEMVER.exec(a).slice(1).map(Number);
17
+ const y = SEMVER.exec(b).slice(1).map(Number);
18
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i];
19
+ return 0;
20
+ };
21
+
22
+ /** served, refused_all, service_role_only ; null : version inconnue */
23
+ function phaseOf(engine) {
24
+ // Une image de dev (0.66.0-rpc) suit la règle de sa version
25
+ engine = String(engine || '').replace(/-.*$/, '');
26
+ if (!SEMVER.test(engine)) return null;
27
+ if (cmp(engine, SERVICE_ROLE_SINCE) >= 0) return 'service_role_only';
28
+ if (cmp(engine, HIDDEN_SINCE) >= 0) return 'refused_all';
29
+ return 'served';
30
+ }
31
+
32
+ const WHY = {
33
+ security_definer: 'SECURITY DEFINER: runs with its owner’s privileges',
34
+ view_owner_rights: 'view without security_invoker: reads with its owner’s privileges',
35
+ materialized_view: 'materialized view: no RLS',
36
+ };
37
+ const quote = (s) => (/^[a-z_][a-z0-9_]*$/.test(s) ? s : `"${String(s).replace(/"/g, '""')}"`);
38
+
39
+ /** Le correctif qui sert de nouveau l'objet à anon et authenticated, sous RLS */
40
+ function fixFor(i) {
41
+ const id = `${quote(i.schema)}.${quote(i.name)}`;
42
+ if (i.reason === 'security_definer') return `alter function ${i.signature || `${id}(…)`} security invoker; (or a SECURITY INVOKER function that calls it and checks auth.uid())`;
43
+ if (i.reason === 'view_owner_rights') return `alter view ${id} set (security_invoker = true);`;
44
+ return 'read it through a SECURITY INVOKER function that returns only allowed rows, or replace it with a table and policies';
45
+ }
46
+
47
+ /** Ce que la version visée change ; { change: lost | regained_service_role | unchanged | none, items } */
48
+ function impact({ current = null, target = null, items = [] } = {}) {
49
+ const from = phaseOf(current);
50
+ const to = phaseOf(target || current);
51
+ const all = items.map((i) => ({ kind: i.kind, schema: i.schema, name: i.name, ...(i.signature ? { signature: i.signature } : {}), reason: i.reason, why: WHY[i.reason] || i.reason, roles: ['anon', 'authenticated'].filter((r) => i[r] !== false), fix: fixFor(i), ...(i.source ? { source: i.source } : {}), ...(i.file ? { file: i.file } : {}) }));
52
+ let change = 'none';
53
+ if (all.length && to !== 'served') {
54
+ if (from === 'served' || from === null) change = 'lost';
55
+ else if (from === 'refused_all' && to === 'service_role_only') change = 'regained_service_role';
56
+ else change = 'unchanged';
57
+ }
58
+ return { current, target: target || current, phase: to, change, count: all.length, items: all };
59
+ }
60
+
61
+ /** La liste lue dans la base de l'engine local (lecture seule) ; null si illisible */
62
+ function readLocal(container) {
63
+ const env = spawnSync('docker', ['exec', container, 'printenv', 'POAD_DATA_SCHEMAS'], { encoding: 'utf8', timeout: 10000 });
64
+ let schemas = String((env.status === 0 && env.stdout) || '').replace(/\s/g, '');
65
+ if (!/^[A-Za-z0-9_,]{1,200}$/.test(schemas)) schemas = 'public';
66
+ const sql = fs.readFileSync(path.join(__dirname, 'api-exposure.sql'), 'utf8');
67
+ const r = spawnSync('docker', ['exec', '-i', container, 'psql', '-X', '-qtA', '-U', 'postgres', '-h', '/var/run/postgresql', '-d', 'postgres', '-v', `schemas=${schemas}`, '-f', '-'], { input: sql, encoding: 'utf8', timeout: 30000 });
68
+ if (r.status !== 0) return null;
69
+ const line = String(r.stdout || '').trim().split('\n').pop();
70
+ try {
71
+ const o = JSON.parse(line);
72
+ return Array.isArray(o.items) ? o : null;
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+
78
+ /** Lignes à montrer (poad deploy, poad upgrade) ; [] si rien à dire */
79
+ function lines(x, chalk, { max = 20 } = {}) {
80
+ if (!x || !x.count || !x.change || x.change === 'none') return [];
81
+ const n = `${x.count} function(s) or view(s)`;
82
+ const head =
83
+ x.change === 'lost'
84
+ ? `⚠ With engine ${x.target}, the API no longer serves ${n} to anon or authenticated: they would let them bypass RLS (403 not_exposed). service_role still gets them; they keep working in SQL.`
85
+ : x.change === 'regained_service_role'
86
+ ? `ℹ ${n} stay refused to anon and authenticated (they would bypass RLS); with engine ${x.target}, service_role gets them again.`
87
+ : `ℹ ${n} are refused to anon and authenticated by the API (they would bypass RLS); service_role gets them.`;
88
+ const out = [x.change === 'lost' ? chalk.yellowBright(` ${head}`) : chalk.cyan(` ${head}`)];
89
+ for (const i of x.items.slice(0, max)) {
90
+ out.push(` ${chalk.bold(`${i.schema}.${i.name}`)} ${chalk.grey(`(${i.why}${i.roles.length ? `; ${i.roles.join(', ')}` : ''}${i.source === 'pending_migration' ? `; created by ${i.file || 'a pending migration'}` : ''})`)}`);
91
+ out.push(chalk.grey(` fix: ${i.fix}`));
92
+ }
93
+ if (x.items.length > max) out.push(chalk.grey(` … and ${x.items.length - max} more (--json lists them all)`));
94
+ return out;
95
+ }
96
+
97
+ module.exports = { HIDDEN_SINCE, SERVICE_ROLE_SINCE, phaseOf, fixFor, impact, readLocal, lines };
@@ -287,15 +287,19 @@ const sheets = {
287
287
  notes: ['Their logs: poad logs flow=<name>, poad logs run=<id>'],
288
288
  },
289
289
  source: {
290
- usage: ['poad source ls [--json]', 'poad source refresh <name> [--force] [--detach]', 'poad source import <file> [--table <table>] [--name <source>] [--key <col,…>] [--existing] [--format …] [--root <path>] [--detach]', 'poad source pull <name> [--force] [--stdout]', 'poad source ls | refresh | import | pull … --env <name> [--project <id>]'],
290
+ usage: ['poad source ls [--json]', 'poad source refresh <name> [--force] [--detach]', 'poad source import <file> [--table <table>] [--name <source>] [--key <col,…> | --key-generated uuid|identity|hash] [--existing] [--format …] [--root <path>] [--sheet <name|n>] [--header <row|none>] [--records <path>] [--expand-until <YYYY-MM-DD>] [--kinds wpt,rte,trk] [--detach]', 'poad source link <table> --host <host> --database <db> --remote <schema.table> --credential <name> [--port <port>] [--sslmode require|verify-full|disable] [--columns <col,…>]', 'poad source link <table> --url <https://…> | --storage <bucket>/<path> [--format csv|json|jsonl|geojson|parquet] [--delimiter <c>] [--no-header] [--encoding utf-8|latin-1|utf-16] [--root <a.b>] [--columns <col,…>]', 'poad source test <name>', 'poad source pull <name> [--force] [--stdout]', 'poad source ls | refresh | import | link | test | pull … --env <name> [--project <id>]'],
291
291
  text: [
292
- 'Sources of the project: tables kept up to date from a URL (JSON, GeoJSON, CSV or JSONL), declared in poad/sources/<name>.yaml (engine 0.64.0+; from engine 0.65.0 a source created by poad is named after its table). The engine creates the table with a migration of poad/migrations (read-only for the application, readable through the API with api: true) and a generated flow source-<name> that fills it: download, read, deposit, apply (upsert by key, removals under a guard).',
292
+ 'Sources of the project: tables kept up to date from a URL (JSON, GeoJSON, CSV, JSONL, ICS calendar, XLSX or ODS spreadsheet, XML such as RSS or Atom, KML, KMZ or GPX), declared in poad/sources/<name>.yaml (engine 0.64.0+; from engine 0.65.0 a source created by poad is named after its table). The engine creates the table with a migration of poad/migrations (read-only for the application, readable through the API with api: true) and a generated flow source-<name> that fills it: download, read, deposit, apply (upsert by key, removals under a guard).',
293
293
  'With --env or --project, the commands act on the project hosted on poad.io (session of poad login, owner only) instead of the local engine: poad.io gives an access of 15 minutes, never shown. Locally, the service_role key of the project, never shown.',
294
294
  ],
295
295
  options: [
296
296
  ['ls', 'each source: mode, table, rows, last synchronisation, next one, problems (declaration, table that differs from it, last failure); exit code 1 if a declaration is invalid'],
297
297
  ['refresh <name>', 'apply the declaration (table, flow), synchronise now and follow the run step by step, then print what changed; exit code 1 if it fails'],
298
- ['import <file>', 'load a CSV, JSON, GeoJSON or JSONL file (.gz accepted, no size limit) into a table: the file goes to the system bucket poad-sources (resumable upload when the storage offers it), the engine reads a sample, proposes the columns and a key, declares an imported source (origin kind: upload) and loads it, streamed; a source is named after its table (poad/sources/<table>.yaml); the source already exists: a new version, same path, then the load. --table <name> (default: the file name; cleaned: lowercase, accents removed, spaces → _, leading digit → t_), --name <source> (kept for compatibility: an existing source of that name gets a new version, otherwise ignored), --key <col,…>, --existing (load into an existing table), --format and --root when the guess is wrong'],
298
+ ['import <file>', 'load a CSV, JSON, GeoJSON, JSONL, ICS, XLSX, ODS, XML, KML, KMZ or GPX file (.gz accepted, no size limit) into a table: the file goes to the system bucket poad-sources (resumable upload when the storage offers it), the engine reads a sample, proposes the columns and a key, declares an imported source (origin kind: upload) and loads it, streamed; a source is named after its table (poad/sources/<table>.yaml); the source already exists: a new version, same path, then the load. --table <name> (default: the file name; cleaned: lowercase, accents removed, spaces → _, leading digit → t_), --name <source> (kept for compatibility: an existing source of that name gets a new version, otherwise ignored), --key <col,…>, --existing (load into an existing table), --format and --root when the guess is wrong. ICS, XLSX, ODS, XML, KML, KMZ and GPX are read by the source-read step itself (engine with meta 1.43.0): --sheet <name or position> and --header <row, or none> for a spreadsheet (default: the first sheet that has rows, first row with two cells or more), --records <path> for XML (channel/item; RSS and Atom are found alone), --expand-until <YYYY-MM-DD> for a calendar (one row per occurrence of repeated events instead of one row per event), --kinds wpt,rte,trk for GPX; what the reader chose is written in the declaration (origin.<format>)'],
299
+ ['--key-generated <kind>', 'import, new table without a natural key: poad adds an id column first, key: { generated: <kind> } in the declaration. uuid (gen_random_uuid()) or identity (sequential bigint): each new version replaces the whole table content in one transaction (the API never sees it empty), under the deletion guard on the net row loss; hash: SHA-256 of the row values, an unchanged row keeps its id (a modified row is removed then added)'],
300
+ ['link <table>', 'a linked table (mode virtual, engine 0.66.0+): a table of another PostgreSQL database read on every query through a foreign table (postgres_fdw), nothing copied. The engine checks the host (internal addresses refused: private network, localhost, link-local, the engine), connects read-only with the credential (a "Database login" of the vault: user and password, never on the command line), proposes the columns of --remote <schema.table> (--columns keeps some of them, remote names), then writes poad/sources/<table>.yaml and the migration of the foreign table. Private: never served by the API'],
301
+ ['link <table> --url | --storage', 'a remote table over a file (mode virtual, engine 0.67.0+): a CSV, JSON (array, --root for where the rows are), JSON-L, GeoJSON (geometry as PostGIS geometry) or Parquet file (.gz accepted) read by DuckDB inside Postgres (duckdb_fdw) on every query, nothing copied: select, where, join with the tables of the project, aggregates; filters are pushed to the file reader. --url <https://…> (internal addresses refused: private network, localhost, link-local, NAT64, the engine, another poad project; no credential, no secret in the address) or --storage <bucket>/<path> (an object of the project storage, local or S3). The engine reads a sample, proposes the columns (--columns keeps some of them, field names), then writes poad/sources/<table>.yaml and the migration of the foreign table. Private: never served by the API'],
302
+ ['test <name>', 'a linked or remote table: check the address again, reattach it and read one row through Postgres (duration, location without its query string); exit code 1 if it cannot be read'],
299
303
  ['pull <name>', 'write the declaration of a source into poad/sources/<name>.yaml: with --env, a source created in the console of poad.io (kept in the project database); commit it, then poad deploy'],
300
304
  ['--force', 'refresh: lift the deletion guard (safety.maxDeletePercent) for this run: the source is right even though many rows go away; pull: replace an existing poad/sources/<name>.yaml'],
301
305
  ['--stdout', 'pull: print the declaration instead of writing the file'],
@@ -306,6 +310,7 @@ const sheets = {
306
310
  ],
307
311
  notes: [
308
312
  'A run that would remove more rows than safety.maxDeletePercent allows (or empty a table) is refused and changes nothing: check the source, then poad source refresh <name> --force.',
313
+ 'A linked or remote table is not refreshed (poad source refresh refuses it): every query reads the remote database or file again. Read it in SQL, through a security_invoker view or a function; a query on a large file is bounded by statement_timeout like any other.',
309
314
  'Their logs: poad logs source=<name>; the run: poad flows show <run_id>. poad deploy sends poad/sources to poad.io.',
310
315
  'Sources can also be created in the console (Sources, New source): locally it writes poad/sources/<name>.yaml; on poad.io it keeps the declaration in the project ("created in the console") until poad source pull <name> --env <name> brings it into the repository.',
311
316
  ],