poad 2.48.0 → 2.49.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.
@@ -0,0 +1,120 @@
1
+ // Appels à l'API de poad.io (plan de contrôle des projets hébergés).
2
+ //
3
+ // base https://poad.io/_poad/cloud, ou POAD_CLOUD_API (tests, autre instance)
4
+ // jeton POAD_ACCESS_TOKEN (CI) d'abord, sinon ~/.poad/credentials.json
5
+ // (poad login) ; envoyé en « Authorization: Bearer », jamais affiché
6
+ // erreurs { error: { code, message } } -> CloudError (status, code, message) ;
7
+ // 401 : « lancez poad login »
8
+ //
9
+ // Le jeton ne part jamais en clair sur le réseau : la base doit être en https,
10
+ // sauf sur la machine elle-même (127.0.0.1, localhost, ::1) pour les tests.
11
+ const DEFAULT_API = 'https://poad.io/_poad/cloud';
12
+
13
+ // Codes de sortie des commandes cloud (repris dans l'aide)
14
+ const EXIT = { ok: 0, error: 1, usage: 2, auth: 3, confirm: 4, failed: 5 };
15
+
16
+ class CloudError extends Error {
17
+ constructor(message, { status = 0, code = 'error', exit } = {}) {
18
+ super(message);
19
+ this.status = status;
20
+ this.code = code;
21
+ this.exit = exit || (status === 401 || code === 'not_logged_in' ? EXIT.auth : EXIT.error);
22
+ }
23
+ }
24
+
25
+ const usageError = (message) => new CloudError(message, { code: 'usage', exit: EXIT.usage });
26
+
27
+ /** Base de l'API, sans « / » final ; refusée si elle n'est ni https ni locale */
28
+ function apiBase(env = process.env) {
29
+ const raw = String(env.POAD_CLOUD_API || DEFAULT_API).trim().replace(/\/+$/, '');
30
+ let u;
31
+ try {
32
+ u = new URL(raw);
33
+ } catch {
34
+ throw new CloudError(`POAD_CLOUD_API is not a URL: ${raw}`, { code: 'bad_api', exit: EXIT.usage });
35
+ }
36
+ const local = ['127.0.0.1', 'localhost', '[::1]', '::1'].includes(u.hostname);
37
+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local)) {
38
+ throw new CloudError(`POAD_CLOUD_API must use https (plain http only on this machine): ${u.origin}`, { code: 'bad_api', exit: EXIT.usage });
39
+ }
40
+ if (u.username || u.password) throw new CloudError('POAD_CLOUD_API must not hold a user or password', { code: 'bad_api', exit: EXIT.usage });
41
+ return raw;
42
+ }
43
+
44
+ /** Jeton à utiliser : { token, source: 'env'|'file', account, expires_at } ou null */
45
+ function currentToken(env = process.env) {
46
+ const fromEnv = String(env.POAD_ACCESS_TOKEN || '').trim();
47
+ if (fromEnv) return { token: fromEnv, source: 'env', account: null, expires_at: null };
48
+ const creds = require('./credentials');
49
+ const entry = creds.get(apiBase(env));
50
+ if (!entry) return null;
51
+ return { token: entry.token, source: 'file', account: entry.account || null, expires_at: entry.expires_at || null };
52
+ }
53
+
54
+ function requireToken(env = process.env) {
55
+ const t = currentToken(env);
56
+ if (!t) throw new CloudError('Not logged in to poad.io: run "poad login" (or set POAD_ACCESS_TOKEN).', { code: 'not_logged_in', exit: EXIT.auth });
57
+ if (t.source === 'file' && t.expires_at && Date.parse(t.expires_at) < Date.now()) {
58
+ throw new CloudError('Your poad.io session has expired: run "poad login".', { code: 'not_logged_in', exit: EXIT.auth });
59
+ }
60
+ return t;
61
+ }
62
+
63
+ const userAgent = () => `poad-cli/${require('../../package.json').version} (${process.platform})`;
64
+
65
+ /**
66
+ * Requête brute : { status, data (JSON ou null), headers }. Ne lève que pour
67
+ * une erreur réseau. body : objet (JSON) ou Buffer (avec contentType).
68
+ */
69
+ async function raw(method, route, { token, body, contentType, headers = {}, timeout = 30000, env = process.env } = {}) {
70
+ const url = `${apiBase(env)}/${String(route).replace(/^\/+/, '')}`;
71
+ const h = { accept: 'application/json', 'user-agent': userAgent(), ...headers };
72
+ if (token) h.authorization = `Bearer ${token}`;
73
+ let payload;
74
+ if (Buffer.isBuffer(body)) {
75
+ payload = body;
76
+ h['content-type'] = contentType || 'application/octet-stream';
77
+ } else if (body !== undefined) {
78
+ payload = JSON.stringify(body);
79
+ h['content-type'] = 'application/json';
80
+ }
81
+ let res;
82
+ try {
83
+ res = await fetch(url, { method, headers: h, body: payload, redirect: 'error', signal: AbortSignal.timeout(timeout) });
84
+ } catch (err) {
85
+ const why = err && err.name === 'TimeoutError' ? 'timeout' : (err && err.cause && err.cause.code) || (err && err.message) || String(err);
86
+ throw new CloudError(`poad.io cannot be reached (${why}).`, { code: 'network_error' });
87
+ }
88
+ const text = await res.text().catch(() => '');
89
+ let data = null;
90
+ if (text) {
91
+ try {
92
+ data = JSON.parse(text);
93
+ } catch {
94
+ data = null;
95
+ }
96
+ }
97
+ return { status: res.status, data, headers: res.headers };
98
+ }
99
+
100
+ /** Message d'erreur lisible d'une réponse { error: { code, message } } */
101
+ function errorOf(res, what) {
102
+ const e = (res.data && res.data.error) || {};
103
+ const code = typeof e.code === 'string' ? e.code : `http_${res.status}`;
104
+ const message = typeof e.message === 'string' && e.message ? e.message : `HTTP ${res.status}`;
105
+ if (res.status === 401) return new CloudError(`poad.io refused the session (${message}): run "poad login".`, { status: 401, code });
106
+ if (res.status === 404) return new CloudError(`${what ? `${what}: ` : ''}not found (${message}).`, { status: 404, code });
107
+ return new CloudError(`${what ? `${what}: ` : ''}${message}${code && !message.includes(code) ? ` (${code})` : ''}`, { status: res.status, code });
108
+ }
109
+
110
+ /** Appel authentifié : la réponse JSON, ou CloudError */
111
+ async function call(method, route, opts = {}) {
112
+ const t = opts.token ? { token: opts.token } : requireToken(opts.env);
113
+ const res = await raw(method, route, { ...opts, token: t.token });
114
+ if (res.status < 200 || res.status >= 300) throw errorOf(res, opts.what);
115
+ return res.data === null ? {} : res.data;
116
+ }
117
+
118
+ const enc = (s) => encodeURIComponent(String(s));
119
+
120
+ module.exports = { DEFAULT_API, EXIT, CloudError, usageError, apiBase, currentToken, requireToken, raw, call, errorOf, enc };
@@ -0,0 +1,63 @@
1
+ // Environnements d'un projet cloud : ses branches (GET v1/projects/:id/branches).
2
+ // Par défaut, l'environnement est la branche git courante si elle existe côté
3
+ // cloud, sinon main ; --env force un environnement (qui doit exister).
4
+ const { spawnSync } = require('child_process');
5
+ const path = require('path');
6
+ const api = require('./api');
7
+ const { checkBranch } = require('./cli');
8
+
9
+ const PRODUCTION = 'main';
10
+
11
+ /** Une branche telle que l'API la rend, ramenée aux champs connus */
12
+ function normalize(b) {
13
+ if (typeof b === 'string') return { name: b, kind: b === PRODUCTION ? 'production' : null, status: null, url: null, created_at: null, engine_version: null };
14
+ if (!b || typeof b !== 'object') return null;
15
+ const name = b.name || b.branch;
16
+ if (typeof name !== 'string' || !name) return null;
17
+ const str = (v) => (typeof v === 'string' ? v : null);
18
+ return { name, kind: str(b.kind) || (name === PRODUCTION ? 'production' : null), status: str(b.status), url: str(b.url), created_at: str(b.created_at), engine_version: str(b.engine_version) };
19
+ }
20
+
21
+ const isProduction = (b) => Boolean(b && (b.name === PRODUCTION || b.kind === 'production'));
22
+
23
+ async function list(projectId) {
24
+ const data = await api.call('GET', `v1/projects/${api.enc(projectId)}/branches`, { what: `environments of ${projectId}` });
25
+ const arr = Array.isArray(data) ? data : Array.isArray(data.branches) ? data.branches : [];
26
+ return arr.map(normalize).filter(Boolean);
27
+ }
28
+
29
+ /** Branche git courante du dossier, ou null (pas de dépôt, HEAD détachée, git absent) */
30
+ function gitBranch(dir) {
31
+ try {
32
+ const r = spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: dir, encoding: 'utf8', timeout: 5000 });
33
+ const b = r.status === 0 ? r.stdout.trim() : '';
34
+ return b && b !== 'HEAD' ? b : null;
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Environnement visé : { branch, production, source: 'option'|'git'|'default', git }
42
+ * wanted valeur de --env (ou undefined)
43
+ * root poad/config.toml du projet local (pour la branche git), ou null
44
+ */
45
+ async function resolve(projectId, { wanted, root } = {}) {
46
+ const branches = await list(projectId);
47
+ if (wanted) {
48
+ checkBranch(wanted);
49
+ const b = branches.find((x) => x.name === wanted);
50
+ if (!b) {
51
+ const known = branches.map((x) => x.name).join(', ') || 'none';
52
+ throw new api.CloudError(`Environment "${wanted}" does not exist on poad.io for ${projectId} (known: ${known}). "poad env create ${wanted}" creates it.`, { status: 404, code: 'branch_not_found' });
53
+ }
54
+ return { branch: b.name, production: isProduction(b), source: 'option', git: null, info: b };
55
+ }
56
+ const git = root ? gitBranch(path.dirname(path.dirname(root))) : null;
57
+ const fromGit = git && branches.find((x) => x.name === git);
58
+ if (fromGit) return { branch: fromGit.name, production: isProduction(fromGit), source: 'git', git, info: fromGit };
59
+ const main = branches.find((x) => x.name === PRODUCTION) || branches.find(isProduction) || { name: PRODUCTION, kind: 'production' };
60
+ return { branch: main.name, production: true, source: 'default', git, info: main };
61
+ }
62
+
63
+ module.exports = { PRODUCTION, normalize, isProduction, list, gitBranch, resolve };
@@ -0,0 +1,226 @@
1
+ // Archive de déploiement : le dossier poad/ en tar.gz, par liste blanche.
2
+ //
3
+ // Entrent (chemins relatifs à poad/, sans préfixe) :
4
+ // dossiers migrations auth storage functions flows api reference variables types
5
+ // credentials/manifest.json noms, types et usages des credentials, sans valeur
6
+ // (les valeurs restent dans le coffre de chaque engine)
7
+ // fichiers seed.sql, config.toml (sans aucune clé secrète : stripSecrets)
8
+ // N'entrent jamais : secrets.toml, .env et .env.*, data/, backups/, node_modules,
9
+ // .git, fichiers cachés de système (.DS_Store…), liens symboliques (ignorés et
10
+ // signalés), fichiers spéciaux.
11
+ //
12
+ // Dernier contrôle : aucune valeur de poad/secrets.toml (secret JWT, clés
13
+ // anon/service_role/admin, mot de passe SMTP, secret de l'exécuteur…) ne doit
14
+ // apparaître dans un fichier de l'archive ; sinon rien n'est envoyé et le
15
+ // fichier est nommé (jamais la valeur).
16
+ //
17
+ // L'archive est reproductible : entrées triées, date et propriétaire fixes.
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const zlib = require('zlib');
21
+
22
+ const DIRS = ['migrations', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'variables', 'types'];
23
+ const FILES = ['seed.sql', 'config.toml'];
24
+ const NEVER = [/^secrets\.toml$/i, /^\.env$/i, /^\.env\..*/i, /^\.DS_Store$/, /^Thumbs\.db$/i, /^desktop\.ini$/i, /~$/, /\.swp$/];
25
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'data', 'backups', '.cache']);
26
+ const LIMITS = { maxBytes: 50 * 1024 * 1024, maxEntries: 5000, maxFile: 20 * 1024 * 1024 };
27
+
28
+ class BundleError extends Error {}
29
+
30
+ // --- Écriture tar (ustar, avec en-tête pax pour les noms longs) ------------------
31
+
32
+ const octal = (n, len) => n.toString(8).padStart(len - 1, '0') + '\0';
33
+
34
+ function header(name, size, { mode = 0o644, type = '0' } = {}) {
35
+ const h = Buffer.alloc(512);
36
+ h.write(name, 0, 100, 'utf8');
37
+ h.write(octal(mode, 8), 100);
38
+ h.write(octal(0, 8), 108);
39
+ h.write(octal(0, 8), 116);
40
+ h.write(octal(size, 12), 124);
41
+ h.write(octal(0, 12), 136);
42
+ h.write(' '.repeat(8), 148);
43
+ h.write(type, 156);
44
+ h.write('ustar\0', 257);
45
+ h.write('00', 263);
46
+ h.write('poad', 265);
47
+ h.write('poad', 297);
48
+ let sum = 0;
49
+ for (const b of h) sum += b;
50
+ h.write(octal(sum, 7) + ' ', 148);
51
+ return h;
52
+ }
53
+
54
+ function paxRecord(key, value) {
55
+ const body = ` ${key}=${value}\n`;
56
+ let len = Buffer.byteLength(body) + 1;
57
+ while (String(len).length + Buffer.byteLength(body) !== len) len = String(len).length + Buffer.byteLength(body);
58
+ return `${len}${body}`;
59
+ }
60
+
61
+ const pad = (n) => Buffer.alloc((512 - (n % 512)) % 512);
62
+
63
+ /** Archive tar de fichiers [{ path, data, mode }] */
64
+ function tar(files) {
65
+ const out = [];
66
+ for (const f of files) {
67
+ const data = Buffer.isBuffer(f.data) ? f.data : Buffer.from(f.data);
68
+ if (Buffer.byteLength(f.path) > 100) {
69
+ const pax = Buffer.from(paxRecord('path', f.path));
70
+ out.push(header('PaxHeader', pax.length, { type: 'x' }), pax, pad(pax.length));
71
+ }
72
+ out.push(header(f.path.slice(0, 100), data.length, { mode: f.mode || 0o644 }), data, pad(data.length));
73
+ }
74
+ out.push(Buffer.alloc(1024));
75
+ return Buffer.concat(out);
76
+ }
77
+
78
+ // --- Contenu ---------------------------------------------------------------------
79
+
80
+ const never = (name) => NEVER.some((re) => re.test(name));
81
+
82
+ /** Fichiers d'un dossier de la liste blanche, récursivement ; liens et spéciaux signalés */
83
+ function walk(base, relDir, files, skipped) {
84
+ const abs = path.join(base, relDir);
85
+ let entries;
86
+ try {
87
+ entries = fs.readdirSync(abs, { withFileTypes: true });
88
+ } catch {
89
+ return;
90
+ }
91
+ for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
92
+ const rel = `${relDir}/${e.name}`;
93
+ if (e.isSymbolicLink()) {
94
+ skipped.push({ path: rel, reason: 'symbolic link' });
95
+ continue;
96
+ }
97
+ if (never(e.name)) {
98
+ skipped.push({ path: rel, reason: 'never sent (secret or local file)' });
99
+ continue;
100
+ }
101
+ if (e.isDirectory()) {
102
+ if (SKIP_DIRS.has(e.name)) skipped.push({ path: rel + '/', reason: 'local folder' });
103
+ else walk(base, rel, files, skipped);
104
+ continue;
105
+ }
106
+ if (!e.isFile()) {
107
+ skipped.push({ path: rel, reason: 'not a regular file' });
108
+ continue;
109
+ }
110
+ files.push(rel);
111
+ }
112
+ }
113
+
114
+ /** Valeurs de poad/secrets.toml (et clés secrètes restées dans config.toml), 8 caractères et plus */
115
+ function localSecrets(poadDir) {
116
+ const values = new Set();
117
+ const collect = (obj) => {
118
+ for (const v of Object.values(obj || {})) {
119
+ if (v && typeof v === 'object') collect(v);
120
+ else if ((typeof v === 'string' || typeof v === 'number') && String(v).length >= 8) values.add(String(v));
121
+ }
122
+ };
123
+ try {
124
+ collect(require('toml').parse(fs.readFileSync(path.join(poadDir, 'secrets.toml'), 'utf8')));
125
+ } catch {}
126
+ try {
127
+ const c = require('toml').parse(fs.readFileSync(path.join(poadDir, 'config.toml'), 'utf8'));
128
+ const pick = { auth: ['secret', 'anon', 'service', 'admin'], smtp: ['pass'], flows: ['runner_token'] };
129
+ for (const [s, keys] of Object.entries(pick)) for (const k of keys) if (c[s] && c[s][k] !== undefined && String(c[s][k]).length >= 8) values.add(String(c[s][k]));
130
+ } catch {}
131
+ return [...values];
132
+ }
133
+
134
+ /** config.toml sans clé secrète (anciens projets) ni secret de l'exécuteur */
135
+ function cleanConfig(text) {
136
+ const { stripSecrets } = require('../config');
137
+ let section = '';
138
+ return stripSecrets(text)
139
+ .split(/\r?\n/)
140
+ .filter((line) => {
141
+ const head = /^\s*\[([^\]]+)\]\s*$/.exec(line);
142
+ if (head) section = head[1].trim();
143
+ const key = /^\s*([A-Za-z_]+)\s*=/.exec(line);
144
+ return !(section === 'flows' && key && key[1] === 'runner_token');
145
+ })
146
+ .join('\n');
147
+ }
148
+
149
+ /** credentials/manifest.json réduit à ce qu'il doit contenir : noms, types, libellés, usages */
150
+ function cleanCredentialsManifest(text) {
151
+ const raw = JSON.parse(text);
152
+ const credentials = (Array.isArray(raw && raw.credentials) ? raw.credentials : [])
153
+ .filter((c) => c && typeof c.name === 'string')
154
+ .map((c) => ({ name: c.name, type: String(c.type || ''), label: String(c.label || '') }));
155
+ const uses = {};
156
+ for (const [k, v] of Object.entries((raw && raw.uses) || {})) if (typeof v === 'string') uses[k] = v;
157
+ return JSON.stringify({ version: 1, credentials, uses }, null, 2) + '\n';
158
+ }
159
+
160
+ /**
161
+ * Construit l'archive du dossier poad/ (poadDir). Renvoie
162
+ * { tgz, files: [{ path, size }], skipped: [{ path, reason }], bytes }.
163
+ */
164
+ function build(poadDir, { limits = LIMITS } = {}) {
165
+ const rels = [];
166
+ const skipped = [];
167
+ for (const d of DIRS) {
168
+ const abs = path.join(poadDir, d);
169
+ let st;
170
+ try {
171
+ st = fs.lstatSync(abs);
172
+ } catch {
173
+ continue;
174
+ }
175
+ if (st.isSymbolicLink()) skipped.push({ path: d + '/', reason: 'symbolic link' });
176
+ else if (st.isDirectory()) walk(poadDir, d, rels, skipped);
177
+ }
178
+ // credentials : le manifeste seul
179
+ const cm = path.join(poadDir, 'credentials', 'manifest.json');
180
+ try {
181
+ const st = fs.lstatSync(cm);
182
+ if (st.isSymbolicLink()) skipped.push({ path: 'credentials/manifest.json', reason: 'symbolic link' });
183
+ else if (st.isFile()) rels.push('credentials/manifest.json');
184
+ } catch {}
185
+ try {
186
+ for (const f of fs.readdirSync(path.join(poadDir, 'credentials'))) if (f !== 'manifest.json') skipped.push({ path: `credentials/${f}`, reason: 'only credentials/manifest.json is sent (values stay in each engine vault)' });
187
+ } catch {}
188
+ for (const f of FILES) {
189
+ const abs = path.join(poadDir, f);
190
+ try {
191
+ const st = fs.lstatSync(abs);
192
+ if (st.isSymbolicLink()) skipped.push({ path: f, reason: 'symbolic link' });
193
+ else if (st.isFile()) rels.push(f);
194
+ } catch {}
195
+ }
196
+ if (!rels.includes('config.toml')) throw new BundleError('poad/config.toml is missing');
197
+ if (rels.length > limits.maxEntries) throw new BundleError(`more than ${limits.maxEntries} files to send`);
198
+
199
+ const secrets = localSecrets(poadDir);
200
+ const files = [];
201
+ let total = 0;
202
+ for (const rel of rels.sort()) {
203
+ const abs = path.join(poadDir, ...rel.split('/'));
204
+ const st = fs.statSync(abs);
205
+ if (st.size > limits.maxFile) throw new BundleError(`${rel} is larger than ${limits.maxFile} bytes`);
206
+ let data = fs.readFileSync(abs);
207
+ if (rel === 'config.toml') data = Buffer.from(cleanConfig(data.toString('utf8')));
208
+ if (rel === 'credentials/manifest.json') {
209
+ try {
210
+ data = Buffer.from(cleanCredentialsManifest(data.toString('utf8')));
211
+ } catch {
212
+ throw new BundleError('poad/credentials/manifest.json is not valid JSON');
213
+ }
214
+ }
215
+ for (const s of secrets) {
216
+ if (data.includes(s)) throw new BundleError(`${rel} contains a secret of poad/secrets.toml: nothing was sent. Remove it from the file (a secret goes in a credential).`);
217
+ }
218
+ total += data.length;
219
+ if (total > limits.maxBytes) throw new BundleError(`the poad/ folder to send is larger than ${limits.maxBytes} bytes`);
220
+ files.push({ path: rel, data, mode: st.mode & 0o111 ? 0o755 : 0o644 });
221
+ }
222
+ const tgz = zlib.gzipSync(tar(files), { level: 9 });
223
+ return { tgz, files: files.map((f) => ({ path: f.path, size: f.data.length })), skipped, bytes: total };
224
+ }
225
+
226
+ module.exports = { build, tar, cleanConfig, cleanCredentialsManifest, localSecrets, BundleError, DIRS, FILES, LIMITS };
@@ -0,0 +1,166 @@
1
+ // Outils communs aux commandes cloud : options, sortie (texte ou --json),
2
+ // erreurs et codes de sortie, confirmation, projet lié.
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { CloudError, EXIT, usageError } = require('./api');
6
+
7
+ /**
8
+ * Options des mots tapés : « --env x », « --env=x », « env=x » pour les
9
+ * options à valeur ; « --yes », « -y », « yes » pour les drapeaux ; le reste
10
+ * est positionnel. Une option à valeur sans valeur : erreur d'usage.
11
+ * spec : { values: ['env', 'name'], flags: ['yes', 'json'], alias: { y: 'yes' } }
12
+ */
13
+ function parse(raw = [], { values = [], flags = [], alias = {} } = {}) {
14
+ const opts = {};
15
+ const positionals = [];
16
+ const words = raw.map(String);
17
+ for (let i = 0; i < words.length; i++) {
18
+ const w = words[i];
19
+ let m = /^--?([A-Za-z][A-Za-z0-9-]*)(?:=(.*))?$/s.exec(w);
20
+ if (m) {
21
+ let key = alias[m[1]] || m[1];
22
+ if (key.startsWith('no-') && flags.includes(key)) {
23
+ opts[key] = true;
24
+ continue;
25
+ }
26
+ if (values.includes(key)) {
27
+ let v = m[2];
28
+ if (v === undefined) {
29
+ if (i + 1 >= words.length || /^--?[A-Za-z]/.test(words[i + 1])) throw usageError(`--${key} needs a value`);
30
+ v = words[++i];
31
+ }
32
+ opts[key] = v;
33
+ } else if (flags.includes(key)) {
34
+ opts[key] = true;
35
+ } else {
36
+ throw usageError(`unknown option ${w.split('=')[0]}`);
37
+ }
38
+ continue;
39
+ }
40
+ m = /^([a-z][a-z-]*)=(.*)$/s.exec(w);
41
+ if (m && values.includes(m[1])) {
42
+ opts[m[1]] = m[2];
43
+ continue;
44
+ }
45
+ positionals.push(w);
46
+ }
47
+ return { opts, positionals };
48
+ }
49
+
50
+ const COMMON_FLAGS = ['json', 'yes'];
51
+
52
+ /** Sortie : log (texte, ignoré en --json), result (JSON en --json) */
53
+ function output(json) {
54
+ const chalk = require('chalk-v2');
55
+ return {
56
+ json,
57
+ chalk,
58
+ log: (...a) => (json ? null : console.log(...a)),
59
+ // En --json, ce qu'il faut tout de même dire à quelqu'un (code de connexion) part sur stderr
60
+ tell: (...a) => (json ? console.error(...a) : console.log(...a)),
61
+ result: (obj) => (json ? console.log(JSON.stringify(obj, null, 2)) : null),
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Exécute une commande cloud : toute erreur devient un message (ou
67
+ * { error: { code, message } } en --json) et un code de sortie.
68
+ */
69
+ async function run(raw, spec, fn) {
70
+ const json = (raw || []).some((w) => w === '--json');
71
+ const out = output(json);
72
+ try {
73
+ const { opts, positionals } = parse(raw, { ...spec, flags: [...COMMON_FLAGS, ...((spec && spec.flags) || [])] });
74
+ out.json = Boolean(opts.json);
75
+ const code = await fn({ opts, positionals, out });
76
+ if (typeof code === 'number' && code !== 0) process.exitCode = code;
77
+ } catch (err) {
78
+ const e = err instanceof CloudError ? err : new CloudError(err && err.message ? err.message : String(err), { code: 'error' });
79
+ process.exitCode = e.exit || EXIT.error;
80
+ if (out.json) console.log(JSON.stringify({ error: { code: e.code, message: e.message } }, null, 2));
81
+ else console.error(out.chalk.redBright(e.message));
82
+ }
83
+ }
84
+
85
+ const interactive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
86
+
87
+ /**
88
+ * Confirmation : true si --yes, sinon la question dans un terminal. Hors
89
+ * terminal (ou en --json) sans --yes : CloudError (code de sortie 4).
90
+ */
91
+ async function confirm(message, { yes, json } = {}) {
92
+ if (yes) return true;
93
+ if (!interactive() || json) throw new CloudError(`Confirmation required: ${message} Add --yes to confirm outside a terminal.`, { code: 'confirmation_required', exit: EXIT.confirm });
94
+ const { confirm: ask } = require('@inquirer/prompts');
95
+ const ok = await ask({ message, default: false }).catch(() => false);
96
+ if (!ok) throw new CloudError('Cancelled: nothing was changed.', { code: 'cancelled', exit: EXIT.confirm });
97
+ return true;
98
+ }
99
+
100
+ // --- Projet local et liaison ([cloud] project de poad/config.toml) --------------
101
+
102
+ const ID_RE = /^[a-z0-9][a-z0-9-]{2,62}$/;
103
+ const BRANCH_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,99}$/;
104
+
105
+ const checkId = (id) => {
106
+ if (!ID_RE.test(String(id || ''))) throw usageError(`"${String(id).slice(0, 80)}" is not a poad.io project id (lowercase letters and digits, as shown by poad cloud projects)`);
107
+ return String(id);
108
+ };
109
+ const checkBranch = (name) => {
110
+ if (!BRANCH_RE.test(String(name || '')) || String(name).includes('..')) throw usageError(`"${String(name).slice(0, 80)}" is not a valid environment name (letters, digits, . _ - /)`);
111
+ return String(name);
112
+ };
113
+
114
+ /** poad/config.toml du dossier courant, ou null */
115
+ const projectRoot = () => require('../findpoad').findPoadDir(process.cwd());
116
+
117
+ /** Lecture seule de config.toml (jamais loadConfig : il crée des secrets) */
118
+ function readToml(root) {
119
+ return require('toml').parse(fs.readFileSync(root, 'utf8'));
120
+ }
121
+
122
+ /** Identifiant du projet cloud lié au projet local, ou null */
123
+ function linkedId(root) {
124
+ try {
125
+ const c = readToml(root);
126
+ const id = c.cloud && c.cloud.project;
127
+ return typeof id === 'string' && ID_RE.test(id) ? id : null;
128
+ } catch {
129
+ return null;
130
+ }
131
+ }
132
+
133
+ function writeLink(root, id) {
134
+ const { setKeys } = require('../tomlfile');
135
+ setKeys(root, 'cloud', { project: checkId(id) });
136
+ require('../projects').record(root);
137
+ }
138
+
139
+ function removeLink(root) {
140
+ const { setKeys, removeSection } = require('../tomlfile');
141
+ const before = linkedId(root);
142
+ setKeys(root, 'cloud', { project: null });
143
+ try {
144
+ const c = readToml(root);
145
+ if (c.cloud && !Object.keys(c.cloud).length) removeSection(root, 'cloud');
146
+ } catch {}
147
+ require('../projects').record(root);
148
+ return before;
149
+ }
150
+
151
+ /**
152
+ * Projet cloud visé : --project, sinon celui lié au dossier courant.
153
+ * Renvoie { id, root } ; erreur d'usage sinon.
154
+ */
155
+ function targetProject(opts = {}) {
156
+ const root = projectRoot();
157
+ if (opts.project) return { id: checkId(opts.project), root };
158
+ if (!root) throw usageError('Not in a poad project folder: cd into one, or pass --project <id>.');
159
+ const id = linkedId(root);
160
+ if (!id) throw usageError('This project is not linked to poad.io: "poad link" (or "poad cloud create").');
161
+ return { id, root };
162
+ }
163
+
164
+ const rel = (p) => path.relative(process.cwd(), p) || '.';
165
+
166
+ module.exports = { parse, output, run, confirm, interactive, ID_RE, checkId, checkBranch, projectRoot, readToml, linkedId, writeLink, removeLink, targetProject, rel };
@@ -0,0 +1,92 @@
1
+ // Jetons de session poad.io de cette machine : ~/.poad/credentials.json.
2
+ //
3
+ // Écrit par poad login seulement, effacé par poad logout. Dossier 0700,
4
+ // fichier 0600, écrit par fichier temporaire (créé en 0600, jamais un fichier
5
+ // déjà là) puis renommage. Un jeton par API (POAD_CLOUD_API), pour que des
6
+ // essais contre une autre instance n'écrasent pas la session de poad.io.
7
+ // Le jeton n'est jamais affiché ni écrit ailleurs ; l'engine ne lit jamais ce
8
+ // fichier.
9
+ //
10
+ // { "version": 1, "sessions": { "<api>": { token, expires_at, account: { id, email }, created_at } } }
11
+ const fs = require('fs');
12
+ const os = require('os');
13
+ const path = require('path');
14
+
15
+ const file = (home = os.homedir()) => path.join(home, '.poad', 'credentials.json');
16
+
17
+ const TOKEN_RE = /^[A-Za-z0-9_.~+/=-]{16,4096}$/;
18
+
19
+ function readAll(home) {
20
+ const f = file(home);
21
+ let text;
22
+ try {
23
+ const st = fs.statSync(f);
24
+ // Lisible par d'autres : ramené à 0600 avant toute lecture
25
+ if (process.platform !== 'win32' && (st.mode & 0o077) !== 0) fs.chmodSync(f, 0o600);
26
+ text = fs.readFileSync(f, 'utf8');
27
+ } catch {
28
+ return { version: 1, sessions: {} };
29
+ }
30
+ try {
31
+ const doc = JSON.parse(text);
32
+ const sessions = {};
33
+ for (const [api, e] of Object.entries((doc && doc.sessions) || {})) {
34
+ if (e && typeof e.token === 'string' && TOKEN_RE.test(e.token)) {
35
+ sessions[api] = {
36
+ token: e.token,
37
+ expires_at: typeof e.expires_at === 'string' ? e.expires_at : null,
38
+ account: e.account && typeof e.account === 'object' ? { id: String(e.account.id || ''), email: String(e.account.email || '') } : null,
39
+ created_at: typeof e.created_at === 'string' ? e.created_at : null,
40
+ };
41
+ }
42
+ }
43
+ return { version: 1, sessions };
44
+ } catch {
45
+ return { version: 1, sessions: {} };
46
+ }
47
+ }
48
+
49
+ function writeAll(doc, home) {
50
+ const f = file(home);
51
+ const dir = path.dirname(f);
52
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
53
+ if (process.platform !== 'win32' && (fs.statSync(dir).mode & 0o077) !== 0) fs.chmodSync(dir, 0o700);
54
+ const tmp = path.join(dir, `.credentials.json.${process.pid}.${Date.now()}.tmp`);
55
+ const out = { version: 1, note: 'poad.io sessions of this machine, written by "poad login". Never shared, never read by the engine.', sessions: doc.sessions };
56
+ fs.writeFileSync(tmp, `${JSON.stringify(out, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
57
+ try {
58
+ fs.chmodSync(tmp, 0o600);
59
+ fs.renameSync(tmp, f);
60
+ } catch (err) {
61
+ try {
62
+ fs.unlinkSync(tmp);
63
+ } catch {}
64
+ throw err;
65
+ }
66
+ }
67
+
68
+ /** Session enregistrée pour cette API, ou null */
69
+ const get = (api, home) => readAll(home).sessions[api] || null;
70
+
71
+ function set(api, { token, expires_at, account }, home) {
72
+ if (typeof token !== 'string' || !TOKEN_RE.test(token)) throw new Error('poad.io sent a token of an unexpected shape: nothing saved');
73
+ const doc = readAll(home);
74
+ doc.sessions[api] = {
75
+ token,
76
+ expires_at: typeof expires_at === 'string' ? expires_at : null,
77
+ account: account ? { id: String(account.id || ''), email: String(account.email || '') } : null,
78
+ created_at: new Date().toISOString(),
79
+ };
80
+ writeAll(doc, home);
81
+ }
82
+
83
+ /** Oublie la session de cette API ; renvoie true si elle existait */
84
+ function remove(api, home) {
85
+ const doc = readAll(home);
86
+ if (!doc.sessions[api]) return false;
87
+ delete doc.sessions[api];
88
+ writeAll(doc, home);
89
+ return true;
90
+ }
91
+
92
+ module.exports = { file, get, set, remove, readAll, TOKEN_RE };