poad 2.47.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.
Files changed (45) hide show
  1. package/global/cli.js +14 -0
  2. package/global/cloud/action.js +37 -0
  3. package/global/cloud/create.js +42 -0
  4. package/global/cloud/index.js +19 -0
  5. package/global/cloud/info.js +37 -0
  6. package/global/cloud/pause.js +2 -0
  7. package/global/cloud/projects.js +32 -0
  8. package/global/cloud/resume.js +2 -0
  9. package/global/cloud/upgrade.js +2 -0
  10. package/global/create.js +4 -4
  11. package/global/init.js +2 -0
  12. package/global/login.js +32 -0
  13. package/global/logout.js +14 -0
  14. package/global/ls.js +2 -0
  15. package/global/projects.js +124 -0
  16. package/global/start.js +2 -0
  17. package/global/whoami.js +13 -0
  18. package/package.json +1 -1
  19. package/poad.js +5 -2
  20. package/project/cli.js +11 -0
  21. package/project/db/index.js +2 -0
  22. package/project/db/pull.js +92 -0
  23. package/project/db/url.js +33 -0
  24. package/project/deploy.js +136 -0
  25. package/project/env/create.js +19 -0
  26. package/project/env/index.js +2 -0
  27. package/project/env/ls.js +24 -0
  28. package/project/env/rm.js +21 -0
  29. package/project/link.js +38 -0
  30. package/project/unlink.js +12 -0
  31. package/project/upgrade.js +1 -0
  32. package/test/cloud.test.js +589 -0
  33. package/test/projects.test.js +167 -0
  34. package/utils/banner.js +3 -0
  35. package/utils/cloud/api.js +120 -0
  36. package/utils/cloud/branches.js +63 -0
  37. package/utils/cloud/bundle.js +226 -0
  38. package/utils/cloud/cli.js +166 -0
  39. package/utils/cloud/credentials.js +92 -0
  40. package/utils/cloud/db.js +34 -0
  41. package/utils/cloud/device.js +66 -0
  42. package/utils/cloud/system.js +45 -0
  43. package/utils/engine.js +1 -0
  44. package/utils/help-details.js +135 -0
  45. package/utils/projects.js +338 -0
@@ -0,0 +1,589 @@
1
+ // poad.io depuis le CLI : login (flux device), session, projets, liaison,
2
+ // environnements, deploy, db url, db pull. Un faux serveur HTTP local tient
3
+ // lieu de poad.io (POAD_CLOUD_API) ; HOME est un dossier temporaire (jamais le
4
+ // ~/.poad de la machine) ; Docker est remplacé par un faux qui échoue.
5
+ const test = require('node:test');
6
+ const assert = require('node:assert');
7
+ const fs = require('fs');
8
+ const http = require('http');
9
+ const path = require('path');
10
+ const zlib = require('zlib');
11
+ const { spawn, spawnSync } = require('child_process');
12
+ const { tmpdir } = require('./helpers');
13
+ const { readTar } = require('../utils/tar');
14
+
15
+ const POAD = path.join(__dirname, '..', 'poad.js');
16
+ const TOKEN = 'poad_pat_TESTTOKEN0123456789abcdefSECRET';
17
+ const ENV_TOKEN = 'poad_pat_FROMENV9876543210zyxwvuSECRET';
18
+ const DB_PASSWORD = 'dbPw-S3cr3t-Value-42';
19
+ const SERVICE_ROLE = 'eyJ-service-role-NEVER-SHOWN';
20
+ const ANON = 'eyJ-anon-public-key';
21
+ const PID = 'abcdef123456';
22
+
23
+ // --- Faux poad.io -------------------------------------------------------------------
24
+
25
+ function fakeCloud(t, behaviour = {}) {
26
+ const state = {
27
+ requests: [],
28
+ pending: behaviour.pending ?? 1,
29
+ projects: [{ id: PID, name: 'demo', region: 'paris', status: 'active', engine_version: '0.38.0', created_at: '2026-11-01T00:00:00Z' }],
30
+ branches: { [PID]: [{ name: 'main', kind: 'production', status: 'active' }, { name: 'dev', kind: 'persistent', status: 'active' }] },
31
+ deploys: {},
32
+ tokens: new Set([TOKEN, ENV_TOKEN]),
33
+ };
34
+ const send = (res, status, body) => {
35
+ res.writeHead(status, { 'content-type': 'application/json' });
36
+ res.end(JSON.stringify(body));
37
+ };
38
+ const err = (res, status, code, message) => send(res, status, { error: { code, message } });
39
+ const server = http.createServer((req, res) => {
40
+ const chunks = [];
41
+ req.on('data', (c) => chunks.push(c));
42
+ req.on('end', () => {
43
+ const body = Buffer.concat(chunks);
44
+ const url = new URL(req.url, 'http://x');
45
+ const route = url.pathname.replace(/^\/_poad\/cloud\//, '');
46
+ const r = { method: req.method, route, query: Object.fromEntries(url.searchParams), headers: req.headers, body };
47
+ state.requests.push(r);
48
+ const json = () => (body.length ? JSON.parse(body.toString('utf8')) : {});
49
+
50
+ // Flux device : sans authentification
51
+ if (req.method === 'POST' && route === 'v1/cli/device') {
52
+ return send(res, 200, { device_code: 'DEVCODE-hidden', user_code: 'WXYZ-1234', verification_uri: 'https://poad.io/device', verification_uri_complete: 'https://poad.io/device?code=WXYZ-1234', interval: 0, expires_in: 600 });
53
+ }
54
+ if (req.method === 'POST' && route === 'v1/cli/token') {
55
+ if (json().device_code !== 'DEVCODE-hidden') return err(res, 400, 'invalid_grant', 'bad code');
56
+ if (behaviour.deny) return err(res, 403, 'access_denied', 'denied');
57
+ if (state.pending-- > 0) return err(res, 428, 'authorization_pending', 'pending');
58
+ return send(res, 200, { token: TOKEN, expires_at: '2099-01-01T00:00:00Z', account: { id: 'acc_1', email: 'dev@example.invalid' } });
59
+ }
60
+
61
+ const auth = /^Bearer (.+)$/.exec(req.headers.authorization || '');
62
+ if (!auth || !state.tokens.has(auth[1])) return err(res, 401, 'unauthorized', 'invalid token');
63
+ r.token = auth[1];
64
+
65
+ if (req.method === 'GET' && route === 'v1/me') return send(res, 200, { id: auth[1] === ENV_TOKEN ? 'acc_env' : 'acc_1', email: auth[1] === ENV_TOKEN ? 'ci@example.invalid' : 'dev@example.invalid' });
66
+ if (req.method === 'GET' && route === 'v1/projects') return send(res, 200, { projects: state.projects });
67
+ if (req.method === 'POST' && route === 'v1/projects') {
68
+ const p = { id: `newproj0000${state.projects.length}`, name: json().name, region: json().region, status: 'creating', engine_version: null };
69
+ state.projects.push(p);
70
+ state.branches[p.id] = [{ name: 'main', kind: 'production' }];
71
+ return send(res, 201, p);
72
+ }
73
+ let m = /^v1\/projects\/([a-z0-9]+)(\/.*)?$/.exec(route);
74
+ if (!m) return err(res, 404, 'not_found', 'no route');
75
+ const [, id, rest = ''] = m;
76
+ const p = state.projects.find((x) => x.id === id);
77
+ if (!p) return err(res, 404, 'project_not_found', 'no such project');
78
+ if (req.method === 'GET' && rest === '') return send(res, 200, p);
79
+ if (req.method === 'GET' && rest === '/keys') return send(res, 200, { url: `https://${id}.poad.io`, anon_key: ANON, service_role: SERVICE_ROLE });
80
+ if (req.method === 'POST' && (rest === '/pause' || rest === '/resume')) return send(res, 200, { status: rest === '/pause' ? 'paused' : 'active' });
81
+ if (req.method === 'GET' && rest === '/engine') return send(res, 200, { current: '0.38.0', offered: '0.39.0', available: true, reason: null });
82
+ if (req.method === 'POST' && rest === '/upgrade') return send(res, 202, { state: 'running', to: json().to });
83
+ if (req.method === 'GET' && rest === '/db-password') return send(res, 200, { user: `postgres.${id}`, password: DB_PASSWORD, host: 'db.poad.io', session_port: 5432, transaction_port: 6543 });
84
+ if (req.method === 'GET' && rest === '/branches') return send(res, 200, { branches: state.branches[id] });
85
+ if (req.method === 'POST' && rest === '/branches') {
86
+ const b = { name: json().name, kind: json().kind, status: 'creating' };
87
+ state.branches[id].push(b);
88
+ return send(res, 201, b);
89
+ }
90
+ m = /^\/branches\/([^/]+)(\/.*)?$/.exec(rest);
91
+ if (m) {
92
+ const branch = decodeURIComponent(m[1]);
93
+ if (!state.branches[id].some((b) => b.name === branch)) return err(res, 404, 'branch_not_found', 'no such branch');
94
+ if (req.method === 'DELETE' && !m[2]) {
95
+ state.branches[id] = state.branches[id].filter((b) => b.name !== branch);
96
+ return send(res, 200, { removed: branch });
97
+ }
98
+ if (req.method === 'POST' && m[2] === '/deploy') {
99
+ const dry = req.headers['x-poad-dry-run'] === '1';
100
+ if (behaviour.async) {
101
+ state.deploys.d1 = 0;
102
+ return send(res, 202, { deploy_id: 'd1', status: 'running' });
103
+ }
104
+ return send(res, 200, { status: 'succeeded', dry_run: dry, migrations: dry ? { applied: [], pending: ['20261101000000_init'], errors: [] } : { applied: ['20261101000000_init'], pending: [], errors: [] } });
105
+ }
106
+ const dm = /^\/deploys\/([^/]+)$/.exec(m[2] || '');
107
+ if (req.method === 'GET' && dm) {
108
+ state.deploys[dm[1]]++;
109
+ if (state.deploys[dm[1]] < 2) return send(res, 200, { deploy_id: dm[1], status: 'running' });
110
+ return send(res, 200, { deploy_id: dm[1], status: 'failed', migrations: { applied: [], pending: [], errors: [{ migration: '20261101000000_init', message: 'relation "x" already exists' }] } });
111
+ }
112
+ }
113
+ return err(res, 404, 'not_found', `no route ${req.method} ${route}`);
114
+ });
115
+ });
116
+ return new Promise((resolve) => {
117
+ server.listen(0, '127.0.0.1', () => {
118
+ t.after(() => server.close());
119
+ state.api = `http://127.0.0.1:${server.address().port}/_poad/cloud`;
120
+ resolve(state);
121
+ });
122
+ });
123
+ }
124
+
125
+ // --- Bac à sable --------------------------------------------------------------------
126
+
127
+ const git = (cwd, ...a) => spawnSync('git', ['-c', 'user.name=poad test', '-c', 'user.email=test@example.invalid', '-c', 'commit.gpgsign=false', ...a], { cwd, encoding: 'utf8' });
128
+
129
+ function sandbox(t, { project = true } = {}) {
130
+ const dir = tmpdir(t, 'poad-cloud-');
131
+ const home = path.join(dir, 'home');
132
+ const bin = path.join(dir, 'bin');
133
+ fs.mkdirSync(home);
134
+ fs.mkdirSync(bin);
135
+ // Pas de npm view avant la commande
136
+ fs.writeFileSync(path.join(home, '.poad_last_check.json'), JSON.stringify({ date: new Date(), version: require('../package.json').version }));
137
+ // Docker de la machine jamais appelé : un faux qui échoue
138
+ fs.writeFileSync(path.join(bin, 'docker'), '#!/bin/sh\nexit 1\n', { mode: 0o755 });
139
+ const app = path.join(dir, 'app');
140
+ fs.mkdirSync(app);
141
+ if (project) {
142
+ const p = path.join(app, 'poad');
143
+ fs.mkdirSync(path.join(p, 'migrations'), { recursive: true });
144
+ fs.mkdirSync(path.join(p, 'functions', 'hello'), { recursive: true });
145
+ fs.mkdirSync(path.join(p, 'credentials'));
146
+ fs.mkdirSync(path.join(p, 'variables'));
147
+ fs.mkdirSync(path.join(p, 'data', 'db'), { recursive: true });
148
+ fs.writeFileSync(path.join(p, 'config.toml'), 'project_id = "demo"\nproject_uuid = "poadcloudtestuuid0001"\nengine = "0.38.0"\n\n[web]\nport = 1\n\n[db]\nport = 2\n\n[auth]\njwt_expiry = 3600\n');
149
+ fs.writeFileSync(path.join(p, 'secrets.toml'), '[auth]\nsecret = "LOCAL-JWT-SECRET-abcdef"\nanon = "LOCAL-ANON-KEY-123456"\nservice = "LOCAL-SERVICE-KEY-654321"\nadmin = "LOCAL-ADMIN-KEY-000000"\n');
150
+ fs.writeFileSync(path.join(p, '.gitignore'), 'data/\nsecrets.toml\nbackups/\n');
151
+ fs.writeFileSync(path.join(p, 'migrations', '20261101000000_init.sql'), 'create table todo (id serial primary key);\n');
152
+ fs.writeFileSync(path.join(p, 'functions', 'hello', 'index.ts'), 'export default { fetch: () => new Response("hi") };\n');
153
+ fs.writeFileSync(path.join(p, 'functions', 'hello', '.env'), 'API_KEY=local-only\n');
154
+ fs.writeFileSync(path.join(p, '.env'), 'X=1\n');
155
+ fs.writeFileSync(path.join(p, 'data', 'db', 'pg'), 'binary');
156
+ fs.symlinkSync('/etc/passwd', path.join(p, 'functions', 'hello', 'leak.txt'));
157
+ fs.writeFileSync(path.join(p, 'credentials', 'manifest.json'), JSON.stringify({ version: 1, credentials: [{ name: 'stripe', type: 'api_key', label: 'Stripe', values: { api_key: 'sk_live_SHOULD_NOT_GO' } }], uses: { 'ai.openai': 'stripe' } }));
158
+ fs.writeFileSync(path.join(p, 'variables', 'manifest.json'), JSON.stringify({ version: 1, variables: [{ name: 'PUBLIC_TITLE', description: '', default: 'Demo' }] }));
159
+ fs.writeFileSync(path.join(p, 'seed.sql'), 'insert into todo default values;\n');
160
+ git(app, 'init', '-q', '-b', 'main');
161
+ git(app, 'add', '-A');
162
+ git(app, 'commit', '-q', '-m', 'init');
163
+ }
164
+ return { dir, home, app, bin, poad: path.join(app, 'poad') };
165
+ }
166
+
167
+ /** Lance le CLI sans bloquer la boucle (le faux serveur tourne dans ce processus) */
168
+ function poad(box, api, args, { env = {}, input = '' } = {}) {
169
+ return new Promise((resolve) => {
170
+ const child = spawn(process.execPath, [POAD, ...args], {
171
+ cwd: box.cwd || box.app,
172
+ env: { ...process.env, HOME: box.home, PATH: `${box.bin}:${process.env.PATH}`, POAD_CLOUD_API: api, POAD_ACCESS_TOKEN: '', NODE_OPTIONS: '', FORCE_COLOR: '0', POAD_DEPLOY_POLL_MS: '10', ...env },
173
+ stdio: ['pipe', 'pipe', 'pipe'],
174
+ });
175
+ let stdout = '';
176
+ let stderr = '';
177
+ child.stdout.on('data', (d) => (stdout += d));
178
+ child.stderr.on('data', (d) => (stderr += d));
179
+ child.stdin.end(input);
180
+ const timer = setTimeout(() => child.kill('SIGKILL'), 20000);
181
+ child.on('close', (status) => {
182
+ clearTimeout(timer);
183
+ resolve({ status, stdout, stderr, all: stdout + stderr });
184
+ });
185
+ });
186
+ }
187
+
188
+ const jsonOf = (r) => JSON.parse(r.stdout);
189
+
190
+ /** Tous les fichiers d'un dossier (liens non suivis) */
191
+ function allFiles(dir) {
192
+ const out = [];
193
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
194
+ const p = path.join(dir, e.name);
195
+ if (e.isDirectory()) out.push(...allFiles(p));
196
+ else if (e.isFile()) out.push(p);
197
+ }
198
+ return out;
199
+ }
200
+
201
+ function login(box, cloud) {
202
+ return poad(box, cloud.api, ['login', '--no-browser']);
203
+ }
204
+
205
+ // --- Tests --------------------------------------------------------------------------
206
+
207
+ test('login : flux device complet, jeton dans credentials.json (0600, dossier 0700), jamais affiché ni écrit ailleurs', async (t) => {
208
+ const box = sandbox(t);
209
+ const cloud = await fakeCloud(t, { pending: 2 });
210
+ const r = await login(box, cloud);
211
+ assert.strictEqual(r.status, 0, r.all);
212
+ assert.match(r.stdout, /WXYZ-1234/);
213
+ assert.match(r.stdout, /https:\/\/poad\.io\/device\?code=WXYZ-1234/);
214
+ assert.match(r.stdout, /Logged in to poad\.io as dev@example\.invalid/);
215
+ assert.ok(!r.all.includes(TOKEN) && !r.all.includes('DEVCODE-hidden'), 'ni le jeton ni le device_code ne s’affichent');
216
+
217
+ const dev = cloud.requests.find((q) => q.route === 'v1/cli/device');
218
+ assert.ok(JSON.parse(dev.body).client_name, 'nom de la machine envoyé');
219
+ assert.strictEqual(cloud.requests.filter((q) => q.route === 'v1/cli/token').length, 3, '2 × 428 puis 200');
220
+
221
+ const file = path.join(box.home, '.poad', 'credentials.json');
222
+ assert.strictEqual(fs.statSync(file).mode & 0o777, 0o600);
223
+ assert.strictEqual(fs.statSync(path.dirname(file)).mode & 0o777, 0o700);
224
+ assert.strictEqual(JSON.parse(fs.readFileSync(file, 'utf8')).sessions[cloud.api].token, TOKEN);
225
+ // Le jeton n'est écrit nulle part ailleurs (HOME, projet)
226
+ for (const f of allFiles(box.dir)) if (f !== file) assert.ok(!fs.readFileSync(f).includes(TOKEN), `jeton trouvé dans ${f}`);
227
+ assert.ok(!fs.readdirSync(path.dirname(file)).some((f) => f.endsWith('.tmp')), 'pas de fichier temporaire laissé');
228
+
229
+ const who = await poad(box, cloud.api, ['whoami', '--json']);
230
+ assert.strictEqual(who.status, 0, who.all);
231
+ assert.deepStrictEqual({ email: jsonOf(who).email, source: jsonOf(who).source }, { email: 'dev@example.invalid', source: 'poad login' });
232
+ assert.strictEqual(cloud.requests.at(-1).headers.authorization, `Bearer ${TOKEN}`);
233
+ assert.ok(!who.all.includes(TOKEN));
234
+
235
+ const out = await poad(box, cloud.api, ['logout']);
236
+ assert.strictEqual(out.status, 0);
237
+ assert.match(out.stdout, /session removed/);
238
+ assert.match(out.stdout, /revoke it on poad\.io/);
239
+ assert.deepStrictEqual(JSON.parse(fs.readFileSync(file, 'utf8')).sessions, {});
240
+ const after = await poad(box, cloud.api, ['whoami']);
241
+ assert.strictEqual(after.status, 3);
242
+ assert.match(after.all, /poad login/);
243
+ });
244
+
245
+ test('login : refus sur poad.io (403) -> code 3, rien d’enregistré ; --json met le code sur stderr', async (t) => {
246
+ const box = sandbox(t);
247
+ const cloud = await fakeCloud(t, { deny: true });
248
+ const r = await poad(box, cloud.api, ['login', '--json']);
249
+ assert.strictEqual(r.status, 3, r.all);
250
+ assert.strictEqual(jsonOf(r).error.code, 'access_denied');
251
+ assert.match(r.stderr, /WXYZ-1234/);
252
+ assert.ok(!fs.existsSync(path.join(box.home, '.poad', 'credentials.json')));
253
+ });
254
+
255
+ test('device.poll : slow_down ajoute 5 s, expired_token et access_denied arrêtent', async (t) => {
256
+ const answers = [];
257
+ const server = http.createServer((req, res) => {
258
+ req.resume();
259
+ req.on('end', () => {
260
+ const [status, code] = answers.shift();
261
+ res.writeHead(status, { 'content-type': 'application/json' });
262
+ res.end(JSON.stringify(status === 200 ? { token: TOKEN, account: { id: 'a', email: 'e' } } : { error: { code, message: code } }));
263
+ });
264
+ });
265
+ await new Promise((r) => server.listen(0, '127.0.0.1', r));
266
+ t.after(() => server.close());
267
+ const prev = process.env.POAD_CLOUD_API;
268
+ process.env.POAD_CLOUD_API = `http://127.0.0.1:${server.address().port}`;
269
+ t.after(() => (prev === undefined ? delete process.env.POAD_CLOUD_API : (process.env.POAD_CLOUD_API = prev)));
270
+ const device = require('../utils/cloud/device');
271
+ const waits = [];
272
+ const sleep = async (ms) => waits.push(ms);
273
+
274
+ answers.push([428, 'authorization_pending'], [429, 'slow_down'], [428, 'authorization_pending'], [200]);
275
+ const got = await device.poll('x', { interval: 5, expiresIn: 600, sleep });
276
+ assert.strictEqual(got.token, TOKEN);
277
+ assert.deepStrictEqual(waits, [5000, 5000, 10000, 10000]);
278
+
279
+ answers.push([410, 'expired_token']);
280
+ await assert.rejects(device.poll('x', { interval: 0, sleep }), (e) => e.code === 'expired_token' && e.exit === 3);
281
+ answers.push([403, 'access_denied']);
282
+ await assert.rejects(device.poll('x', { interval: 0, sleep }), (e) => e.code === 'access_denied' && e.exit === 3);
283
+ // Le délai du code est respecté même si le serveur répond toujours « en attente »
284
+ let clock = 0;
285
+ answers.push([428, 'authorization_pending'], [428, 'authorization_pending'], [428, 'authorization_pending']);
286
+ await assert.rejects(device.poll('x', { interval: 5, expiresIn: 12, sleep: async (ms) => (clock += ms), now: () => clock }), (e) => e.code === 'expired_token');
287
+ });
288
+
289
+ test('POAD_ACCESS_TOKEN passe avant la session enregistrée ; 401 -> « poad login », code 3 ; http refusé hors de la machine', async (t) => {
290
+ const box = sandbox(t);
291
+ const cloud = await fakeCloud(t);
292
+ await login(box, cloud);
293
+ const r = await poad(box, cloud.api, ['whoami', '--json'], { env: { POAD_ACCESS_TOKEN: ENV_TOKEN } });
294
+ assert.strictEqual(r.status, 0, r.all);
295
+ assert.strictEqual(jsonOf(r).email, 'ci@example.invalid');
296
+ assert.strictEqual(jsonOf(r).source, 'POAD_ACCESS_TOKEN');
297
+ assert.ok(!r.all.includes(ENV_TOKEN));
298
+
299
+ const bad = await poad(box, cloud.api, ['cloud', 'projects'], { env: { POAD_ACCESS_TOKEN: 'poad_pat_revoked_0000000000000' } });
300
+ assert.strictEqual(bad.status, 3);
301
+ assert.match(bad.stderr, /run "poad login"/);
302
+
303
+ const plain = await poad(box, 'http://poad.example.invalid/_poad/cloud', ['whoami']);
304
+ assert.strictEqual(plain.status, 2);
305
+ assert.match(plain.stderr, /must use https/);
306
+ });
307
+
308
+ test('cloud projects, link, unlink, cloud info (jamais service_role), poad projects montre la liaison', async (t) => {
309
+ const box = sandbox(t);
310
+ const cloud = await fakeCloud(t);
311
+ await login(box, cloud);
312
+ const list = await poad(box, cloud.api, ['cloud', 'projects', '--json']);
313
+ assert.strictEqual(list.status, 0, list.all);
314
+ assert.deepStrictEqual(jsonOf(list).map((p) => [p.id, p.linked]), [[PID, false]]);
315
+
316
+ const notLinked = await poad(box, cloud.api, ['deploy', '--json']);
317
+ assert.strictEqual(notLinked.status, 2);
318
+ assert.match(jsonOf(notLinked).error.message, /poad link/);
319
+
320
+ // Sans identifiant ni terminal : on dit quoi taper
321
+ const ask = await poad(box, cloud.api, ['link']);
322
+ assert.strictEqual(ask.status, 2);
323
+ assert.match(ask.stderr, new RegExp(`poad link <id> \\(yours: ${PID}\\)`));
324
+
325
+ const missing = await poad(box, cloud.api, ['link', 'zzzzzzzzzzzz']);
326
+ assert.strictEqual(missing.status, 1);
327
+ assert.match(missing.stderr, /not found/);
328
+
329
+ const link = await poad(box, cloud.api, ['link', PID]);
330
+ assert.strictEqual(link.status, 0, link.all);
331
+ const config = fs.readFileSync(path.join(box.poad, 'config.toml'), 'utf8');
332
+ assert.match(config, new RegExp(`\\[cloud\\]\\nproject = "${PID}"`));
333
+ assert.ok(!/token|password|key/i.test(config.split('[cloud]')[1]), 'aucun secret dans [cloud]');
334
+ assert.match(config, /jwt_expiry = 3600/, 'le reste du fichier est gardé');
335
+
336
+ const info = await poad(box, cloud.api, ['cloud', 'info']);
337
+ assert.strictEqual(info.status, 0, info.all);
338
+ assert.match(info.stdout, new RegExp(`https://${PID}\\.poad\\.io`));
339
+ assert.match(info.stdout, new RegExp(ANON));
340
+ assert.match(info.stdout, /0\.38\.0/);
341
+ const infoJson = await poad(box, cloud.api, ['cloud', 'info', '--json']);
342
+ assert.strictEqual(jsonOf(infoJson).anon_key, ANON);
343
+ assert.ok(!info.all.includes(SERVICE_ROLE) && !infoJson.all.includes(SERVICE_ROLE), 'service_role jamais affichée');
344
+
345
+ const projects = await poad(box, cloud.api, ['projects', '--json']);
346
+ assert.strictEqual(projects.status, 0, projects.all);
347
+ assert.strictEqual(jsonOf(projects).find((p) => p.id === 'poadcloudtestuuid0001').cloud, PID);
348
+ const table = await poad(box, cloud.api, ['projects']);
349
+ assert.match(table.stdout, /POAD\.IO/);
350
+ assert.match(table.stdout, new RegExp(PID));
351
+ assert.ok(!fs.readFileSync(path.join(box.home, '.poad', 'projects.json'), 'utf8').includes(TOKEN));
352
+
353
+ const un = await poad(box, cloud.api, ['unlink', '--json']);
354
+ assert.deepStrictEqual(jsonOf(un), { unlinked: PID });
355
+ assert.ok(!fs.readFileSync(path.join(box.poad, 'config.toml'), 'utf8').includes('[cloud]'));
356
+ const again = await poad(box, cloud.api, ['projects', '--json']);
357
+ assert.strictEqual(jsonOf(again).find((p) => p.id === 'poadcloudtestuuid0001').cloud, null);
358
+ });
359
+
360
+ test('cloud create : crée et lie le dossier ; pause demande confirmation ; upgrade vers la version proposée', async (t) => {
361
+ const box = sandbox(t);
362
+ const cloud = await fakeCloud(t);
363
+ await login(box, cloud);
364
+ const r = await poad(box, cloud.api, ['cloud', 'create', '--json']);
365
+ assert.strictEqual(r.status, 0, r.all);
366
+ assert.strictEqual(jsonOf(r).link, 'linked');
367
+ const sent = cloud.requests.find((q) => q.method === 'POST' && q.route === 'v1/projects');
368
+ assert.deepStrictEqual(JSON.parse(sent.body), { name: 'demo', region: 'paris' });
369
+ assert.match(fs.readFileSync(path.join(box.poad, 'config.toml'), 'utf8'), /project = "newproj00001"/);
370
+ assert.match(fs.readFileSync(path.join(box.poad, 'config.toml'), 'utf8'), /\[cloud\]/);
371
+
372
+ // Un dossier déjà lié le reste
373
+ const second = await poad(box, cloud.api, ['cloud', 'create', '--name', 'other', '--json']);
374
+ assert.strictEqual(jsonOf(second).link, 'kept');
375
+
376
+ const pause = await poad(box, cloud.api, ['cloud', 'pause']);
377
+ assert.strictEqual(pause.status, 4);
378
+ assert.match(pause.stderr, /--yes/);
379
+ assert.ok(!cloud.requests.some((q) => q.route.endsWith('/pause')));
380
+ const paused = await poad(box, cloud.api, ['cloud', 'pause', '--yes', '--json']);
381
+ assert.strictEqual(paused.status, 0, paused.all);
382
+ assert.strictEqual(jsonOf(paused).status, 'paused');
383
+
384
+ const up = await poad(box, cloud.api, ['cloud', 'upgrade', '--yes', '--json', '--project', PID]);
385
+ assert.strictEqual(up.status, 0, up.all);
386
+ assert.deepStrictEqual([jsonOf(up).from, jsonOf(up).to], ['0.38.0', '0.39.0']);
387
+ assert.deepStrictEqual(JSON.parse(cloud.requests.find((q) => q.route.endsWith('/upgrade')).body), { to: '0.39.0' });
388
+ });
389
+
390
+ test('env ls / create / rm : confirmation, --yes, main jamais supprimé', async (t) => {
391
+ const box = sandbox(t);
392
+ const cloud = await fakeCloud(t);
393
+ await login(box, cloud);
394
+ await poad(box, cloud.api, ['link', PID]);
395
+ const ls = await poad(box, cloud.api, ['env', 'ls', '--json']);
396
+ assert.strictEqual(ls.status, 0, ls.all);
397
+ assert.deepStrictEqual(jsonOf(ls).map((b) => [b.name, b.production, b.default]), [['main', true, true], ['dev', false, false]]);
398
+
399
+ const c = await poad(box, cloud.api, ['env', 'create', 'feature/x', '--kind', 'preview', '--json']);
400
+ assert.strictEqual(c.status, 0, c.all);
401
+ assert.deepStrictEqual(JSON.parse(cloud.requests.at(-1).body), { name: 'feature/x', kind: 'preview' });
402
+ const badKind = await poad(box, cloud.api, ['env', 'create', 'y', '--kind', 'forever']);
403
+ assert.strictEqual(badKind.status, 2);
404
+
405
+ const noYes = await poad(box, cloud.api, ['env', 'rm', 'feature/x']);
406
+ assert.strictEqual(noYes.status, 4);
407
+ assert.ok(!cloud.requests.some((q) => q.method === 'DELETE'));
408
+ const rm = await poad(box, cloud.api, ['env', 'rm', 'feature/x', '--yes', '--json']);
409
+ assert.strictEqual(rm.status, 0, rm.all);
410
+ assert.strictEqual(cloud.requests.at(-1).route, `v1/projects/${PID}/branches/feature%2Fx`);
411
+ const main = await poad(box, cloud.api, ['env', 'rm', 'main', '--yes']);
412
+ assert.strictEqual(main.status, 2);
413
+ assert.match(main.stderr, /production/);
414
+ });
415
+
416
+ test('deploy : archive sans secrets.toml, .env, data/ ni lien ; config et credentials nettoyés ; confirmation de la production', async (t) => {
417
+ const box = sandbox(t);
418
+ const cloud = await fakeCloud(t);
419
+ await login(box, cloud);
420
+ await poad(box, cloud.api, ['link', PID]);
421
+ git(box.app, 'commit', '-qam', 'link');
422
+ const sha = git(box.app, 'rev-parse', 'HEAD').stdout.trim();
423
+
424
+ // Production sans --yes, hors terminal : rien n'est envoyé
425
+ const refused = await poad(box, cloud.api, ['deploy']);
426
+ assert.strictEqual(refused.status, 4, refused.all);
427
+ assert.match(refused.stdout, /main \(production\)/);
428
+ assert.ok(!cloud.requests.some((q) => q.route.endsWith('/deploy')));
429
+
430
+ const r = await poad(box, cloud.api, ['deploy', '--yes', '--json']);
431
+ assert.strictEqual(r.status, 0, r.all);
432
+ const out = jsonOf(r);
433
+ assert.strictEqual(out.env, 'main');
434
+ assert.strictEqual(out.production, true);
435
+ assert.strictEqual(out.sha, sha);
436
+ assert.deepStrictEqual(out.migrations.applied, ['20261101000000_init']);
437
+
438
+ const req = cloud.requests.find((q) => q.route.endsWith('/deploy'));
439
+ assert.strictEqual(req.route, `v1/projects/${PID}/branches/main/deploy`);
440
+ assert.strictEqual(req.headers['content-type'], 'application/gzip');
441
+ assert.strictEqual(req.headers['x-poad-sha'], sha);
442
+ assert.strictEqual(req.headers['x-poad-dry-run'], undefined);
443
+ const entries = readTar(zlib.gunzipSync(req.body), { strip: 0 });
444
+ const names = entries.map((e) => e.path).sort();
445
+ assert.deepStrictEqual(names, ['config.toml', 'credentials/manifest.json', 'functions/hello/index.ts', 'migrations/20261101000000_init.sql', 'seed.sql', 'variables/manifest.json']);
446
+ const raw = zlib.gunzipSync(req.body).toString('latin1');
447
+ for (const secret of ['LOCAL-JWT-SECRET', 'LOCAL-ANON-KEY', 'LOCAL-SERVICE-KEY', 'sk_live_SHOULD_NOT_GO', 'API_KEY=local-only', 'root:']) assert.ok(!raw.includes(secret), `${secret} dans l’archive`);
448
+ const creds = JSON.parse(entries.find((e) => e.path === 'credentials/manifest.json').data);
449
+ assert.deepStrictEqual(creds, { version: 1, credentials: [{ name: 'stripe', type: 'api_key', label: 'Stripe' }], uses: { 'ai.openai': 'stripe' } });
450
+ assert.ok(out.skipped.some((s) => s.path === 'functions/hello/leak.txt' && s.reason === 'symbolic link'));
451
+ assert.ok(!r.all.includes(TOKEN));
452
+ });
453
+
454
+ test('deploy : branche git présente sur poad.io = environnement par défaut ; --dry-run ; arbre sale averti, sans commit', async (t) => {
455
+ const box = sandbox(t);
456
+ const cloud = await fakeCloud(t);
457
+ await login(box, cloud);
458
+ await poad(box, cloud.api, ['link', PID]);
459
+ git(box.app, 'commit', '-qam', 'link');
460
+ git(box.app, 'checkout', '-qb', 'dev');
461
+ const r = await poad(box, cloud.api, ['deploy']);
462
+ assert.strictEqual(r.status, 0, r.all);
463
+ assert.match(r.stdout, /→ dev\s+\(git branch\)/);
464
+ assert.ok(cloud.requests.at(-1).route.endsWith('/branches/dev/deploy'), 'pas de confirmation hors production');
465
+
466
+ fs.appendFileSync(path.join(box.poad, 'migrations', '20261101000000_init.sql'), '-- change\n');
467
+ const dry = await poad(box, cloud.api, ['deploy', '--env', 'main', '--dry-run', '--json']);
468
+ assert.strictEqual(dry.status, 0, dry.all);
469
+ const req = cloud.requests.at(-1);
470
+ assert.ok(req.route.endsWith('/branches/main/deploy'));
471
+ assert.strictEqual(req.headers['x-poad-dry-run'], '1');
472
+ assert.strictEqual(req.headers['x-poad-sha'], undefined, 'pas de commit quand poad/ a des changements');
473
+ assert.strictEqual(jsonOf(dry).dirty, true);
474
+ assert.deepStrictEqual(jsonOf(dry).migrations.pending, ['20261101000000_init']);
475
+ const text = await poad(box, cloud.api, ['deploy', '--env', 'main', '--dry-run']);
476
+ assert.match(text.stdout, /uncommitted change/);
477
+ assert.match(text.stdout, /Dry run: nothing changed/);
478
+
479
+ const unknown = await poad(box, cloud.api, ['deploy', '--env', 'nope', '--yes']);
480
+ assert.strictEqual(unknown.status, 1);
481
+ assert.match(unknown.stderr, /poad env create nope/);
482
+ });
483
+
484
+ test('deploy : asynchrone suivi jusqu’à l’échec (code 5) ; un secret local dans un fichier : rien n’est envoyé', async (t) => {
485
+ const box = sandbox(t);
486
+ const cloud = await fakeCloud(t, { async: true });
487
+ await login(box, cloud);
488
+ await poad(box, cloud.api, ['link', PID]);
489
+ const r = await poad(box, cloud.api, ['deploy', '--yes']);
490
+ assert.strictEqual(r.status, 5, r.all);
491
+ assert.match(r.stdout, /deploy d1: running/);
492
+ assert.match(r.stdout, /relation "x" already exists/);
493
+ assert.match(r.stdout, /Deploy failed/);
494
+ assert.ok(cloud.requests.filter((q) => q.route.endsWith('/deploys/d1')).length >= 2);
495
+
496
+ const before = cloud.requests.filter((q) => q.route.endsWith('/deploy')).length;
497
+ fs.writeFileSync(path.join(box.poad, 'functions', 'hello', 'index.ts'), 'const k = "LOCAL-SERVICE-KEY-654321";\n');
498
+ const leak = await poad(box, cloud.api, ['deploy', '--yes', '--json']);
499
+ assert.strictEqual(leak.status, 1, leak.all);
500
+ assert.match(jsonOf(leak).error.message, /functions\/hello\/index\.ts contains a secret of poad\/secrets\.toml/);
501
+ assert.ok(!leak.all.includes('LOCAL-SERVICE-KEY-654321'), 'la valeur n’est jamais affichée');
502
+ assert.strictEqual(cloud.requests.filter((q) => q.route.endsWith('/deploy')).length, before);
503
+ });
504
+
505
+ test('db url : mot de passe masqué par défaut, --show-password l’affiche, mode transaction sur 6543', async (t) => {
506
+ const box = sandbox(t);
507
+ const cloud = await fakeCloud(t);
508
+ await login(box, cloud);
509
+ await poad(box, cloud.api, ['link', PID]);
510
+ const r = await poad(box, cloud.api, ['db', 'url']);
511
+ assert.strictEqual(r.status, 0, r.all);
512
+ assert.match(r.stdout, new RegExp(`postgresql://postgres\\.${PID}:•+@db\\.poad\\.io:5432/postgres\\?sslmode=require`));
513
+ assert.match(r.stdout, /--show-password/);
514
+ assert.ok(!r.all.includes(DB_PASSWORD));
515
+ const j = await poad(box, cloud.api, ['db', 'url', '--mode', 'transaction', '--json']);
516
+ assert.ok(!j.all.includes(DB_PASSWORD));
517
+ assert.match(jsonOf(j).url, /:6543\//);
518
+ const shown = await poad(box, cloud.api, ['db', 'url', '--show-password']);
519
+ assert.strictEqual(shown.stdout.trim(), `postgresql://postgres.${PID}:${DB_PASSWORD}@db.poad.io:5432/postgres?sslmode=require`);
520
+ assert.strictEqual(cloud.requests.at(-1).query.purpose, 'reveal');
521
+ const bad = await poad(box, cloud.api, ['db', 'url', '--mode', 'pool']);
522
+ assert.strictEqual(bad.status, 2);
523
+ const dev = await poad(box, cloud.api, ['db', 'url', '--env', 'dev']);
524
+ assert.strictEqual(dev.status, 1);
525
+ assert.match(dev.stderr, /production database only/);
526
+ });
527
+
528
+ test('db pull : pg_dump --schema-only avec PGPASSWORD (jamais en argument), nouvelle migration à chaque fois', async (t) => {
529
+ const box = sandbox(t);
530
+ const cloud = await fakeCloud(t);
531
+ await login(box, cloud);
532
+ await poad(box, cloud.api, ['link', PID]);
533
+ const argsFile = path.join(box.dir, 'pg_dump.args');
534
+ const fake = path.join(box.bin, 'fake_pg_dump');
535
+ fs.writeFileSync(
536
+ fake,
537
+ `#!/bin/sh\nprintf '%s\\n' "$@" > "${argsFile}"\necho "PW=$PGPASSWORD SSL=$PGSSLMODE" >> "${argsFile}"\ncat <<'SQL'\n\\\\restrict abc\nSET statement_timeout = 0;\nSELECT pg_catalog.set_config('search_path', '', false);\nCREATE TABLE public.todo (id integer NOT NULL);\nSQL\n`,
538
+ { mode: 0o755 },
539
+ );
540
+ const before = fs.readdirSync(path.join(box.poad, 'migrations'));
541
+ const original = fs.readFileSync(path.join(box.poad, 'migrations', before[0]), 'utf8');
542
+ const r = await poad(box, cloud.api, ['db', 'pull', '--json'], { env: { POAD_PG_DUMP: fake } });
543
+ assert.strictEqual(r.status, 0, r.all);
544
+ const written = jsonOf(r).written;
545
+ assert.match(written, /_cloud_main_schema\.sql$/);
546
+ const sql = fs.readFileSync(path.join(box.app, written), 'utf8');
547
+ assert.match(sql, /CREATE TABLE public\.todo/);
548
+ assert.ok(!/\\restrict|SET statement_timeout|set_config/.test(sql), 'ni commande psql ni réglage de session');
549
+ const argv = fs.readFileSync(argsFile, 'utf8');
550
+ assert.match(argv, /--schema-only/);
551
+ assert.match(argv, new RegExp(`postgres\\.${PID}`));
552
+ assert.ok(argv.split('\n').filter((l) => !l.startsWith('PW=')).every((l) => !l.includes(DB_PASSWORD)), 'mot de passe jamais en argument');
553
+ assert.match(argv, new RegExp(`PW=${DB_PASSWORD} SSL=require`));
554
+ assert.ok(!r.all.includes(DB_PASSWORD));
555
+
556
+ const again = await poad(box, cloud.api, ['db', 'pull', '--json'], { env: { POAD_PG_DUMP: fake } });
557
+ assert.notStrictEqual(jsonOf(again).written, written, 'jamais écrasée');
558
+ assert.strictEqual(fs.readFileSync(path.join(box.poad, 'migrations', before[0]), 'utf8'), original);
559
+ assert.strictEqual(fs.readdirSync(path.join(box.poad, 'migrations')).length, 3);
560
+ });
561
+
562
+ test('bundle : archive reproductible, noms longs, refus hors liste blanche', (t) => {
563
+ const box = sandbox(t);
564
+ const bundle = require('../utils/cloud/bundle');
565
+ const long = path.join(box.poad, 'functions', 'a'.repeat(60), 'b'.repeat(60));
566
+ fs.mkdirSync(long, { recursive: true });
567
+ fs.writeFileSync(path.join(long, 'index.ts'), 'x');
568
+ fs.mkdirSync(path.join(box.poad, 'functions', 'hello', 'node_modules'));
569
+ fs.writeFileSync(path.join(box.poad, 'functions', 'hello', 'node_modules', 'x.js'), 'x');
570
+ fs.writeFileSync(path.join(box.poad, 'keycloak.json'), '{}');
571
+ const a = bundle.build(box.poad);
572
+ const b = bundle.build(box.poad);
573
+ assert.ok(a.tgz.equals(b.tgz), 'même contenu, même archive');
574
+ const names = readTar(zlib.gunzipSync(a.tgz), { strip: 0 }).map((e) => e.path);
575
+ assert.ok(names.includes(`functions/${'a'.repeat(60)}/${'b'.repeat(60)}/index.ts`));
576
+ assert.ok(!names.some((n) => n.includes('node_modules') || n === 'keycloak.json' || n.startsWith('data/')));
577
+ assert.match(bundle.cleanConfig('[auth]\nsecret = "s"\njwt_expiry = 1\n[flows]\nrunner_token = "t"\nrunner = true\n'), /^\[auth\]\njwt_expiry = 1\n\[flows\]\nrunner = true\n$/);
578
+ });
579
+
580
+ test('options : valeur manquante et option inconnue -> code 2', async (t) => {
581
+ const box = sandbox(t);
582
+ const cloud = await fakeCloud(t);
583
+ const r = await poad(box, cloud.api, ['deploy', '--env']);
584
+ assert.strictEqual(r.status, 2);
585
+ assert.match(r.stderr, /--env needs a value/);
586
+ const u = await poad(box, cloud.api, ['whoami', '--bogus', '--json']);
587
+ assert.strictEqual(u.status, 2);
588
+ assert.strictEqual(jsonOf(u).error.code, 'usage');
589
+ });