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,34 @@
1
+ // Connexion directe à la base d'un projet poad.io (passerelle db.poad.io).
2
+ // GET v1/projects/:id/db-password?purpose=copy|reveal|pull
3
+ // -> { user, password, host, session_port, transaction_port }
4
+ // Le mot de passe n'est gardé qu'en mémoire ; il ne s'affiche qu'avec
5
+ // --show-password (poad db url) et ne passe jamais en argument d'un processus.
6
+ const api = require('./api');
7
+
8
+ const HOST = 'db.poad.io';
9
+ const PORTS = { session: 5432, transaction: 6543 };
10
+ const MASK = '••••••••';
11
+
12
+ async function credentials(id, { env, purpose = 'copy' } = {}) {
13
+ if (env && !env.production) {
14
+ // Pas encore de route par environnement côté serveur : on ne devine pas
15
+ throw new api.CloudError(`The database of the environment "${env.branch}" is not reachable from the CLI yet (poad.io gives the password of the production database only). Use --env main.`, { code: 'unsupported' });
16
+ }
17
+ const d = await api.call('GET', `v1/projects/${api.enc(id)}/db-password?purpose=${encodeURIComponent(purpose)}`, { what: 'database password' });
18
+ if (typeof d.password !== 'string' || !d.password) throw new api.CloudError('poad.io sent no database password.', { code: 'bad_response' });
19
+ const port = (mode) => Number(mode === 'transaction' ? d.transaction_port : d.session_port) || PORTS[mode];
20
+ return {
21
+ user: typeof d.user === 'string' && d.user ? d.user : `postgres.${id}`,
22
+ password: d.password,
23
+ host: typeof d.host === 'string' && /^[A-Za-z0-9.-]+$/.test(d.host) ? d.host : HOST,
24
+ port,
25
+ };
26
+ }
27
+
28
+ /** postgresql://<user>:<mot de passe ou masque>@<hôte>:<port>/postgres?sslmode=require */
29
+ function url(c, mode = 'session', { show = false } = {}) {
30
+ const pw = show ? encodeURIComponent(c.password) : MASK;
31
+ return `postgresql://${encodeURIComponent(c.user)}:${pw}@${c.host}:${c.port(mode)}/postgres?sslmode=require`;
32
+ }
33
+
34
+ module.exports = { HOST, PORTS, MASK, credentials, url };
@@ -0,0 +1,66 @@
1
+ // Connexion par appareil (RFC 8628) à poad.io.
2
+ // POST v1/cli/device { client_name } -> { device_code, user_code, verification_uri,
3
+ // verification_uri_complete, interval, expires_in }
4
+ // POST v1/cli/token { device_code } -> 200 { token, expires_at, account: { id, email } }
5
+ // 428 authorization_pending : on attend
6
+ // 429 slow_down : intervalle + 5 s
7
+ // 410 expired_token : le code a expiré
8
+ // 403 access_denied : refusé sur poad.io
9
+ // device_code et token ne sont jamais affichés.
10
+ const os = require('os');
11
+ const api = require('./api');
12
+
13
+ const { CloudError, EXIT } = api;
14
+
15
+ async function start({ clientName = os.hostname() } = {}) {
16
+ const res = await api.raw('POST', 'v1/cli/device', { body: { client_name: String(clientName).slice(0, 100) } });
17
+ if (res.status < 200 || res.status >= 300) throw api.errorOf(res, 'login');
18
+ const d = res.data || {};
19
+ if (typeof d.device_code !== 'string' || typeof d.user_code !== 'string') throw new CloudError('poad.io answered the login request without a code.', { code: 'bad_response' });
20
+ const interval = Number.isFinite(Number(d.interval)) && Number(d.interval) >= 0 ? Number(d.interval) : 5;
21
+ const expiresIn = Number.isFinite(Number(d.expires_in)) && Number(d.expires_in) > 0 ? Number(d.expires_in) : 900;
22
+ return {
23
+ device_code: d.device_code,
24
+ user_code: d.user_code,
25
+ verification_uri: typeof d.verification_uri === 'string' ? d.verification_uri : null,
26
+ verification_uri_complete: typeof d.verification_uri_complete === 'string' ? d.verification_uri_complete : null,
27
+ interval,
28
+ expires_in: expiresIn,
29
+ };
30
+ }
31
+
32
+ const sleepMs = (ms) => new Promise((r) => setTimeout(r, ms));
33
+
34
+ /**
35
+ * Attend la validation sur poad.io. Renvoie { token, expires_at, account }.
36
+ * sleep et now sont remplaçables (tests).
37
+ */
38
+ async function poll(deviceCode, { interval = 5, expiresIn = 900, sleep = sleepMs, now = Date.now, onWait } = {}) {
39
+ let wait = interval;
40
+ const deadline = now() + expiresIn * 1000;
41
+ for (;;) {
42
+ await sleep(wait * 1000);
43
+ const res = await api.raw('POST', 'v1/cli/token', { body: { device_code: deviceCode } });
44
+ const code = res.data && res.data.error && res.data.error.code;
45
+ if (res.status === 200) {
46
+ const d = res.data || {};
47
+ if (typeof d.token !== 'string' || !d.token) throw new CloudError('poad.io validated the login but sent no token.', { code: 'bad_response' });
48
+ return { token: d.token, expires_at: typeof d.expires_at === 'string' ? d.expires_at : null, account: d.account && typeof d.account === 'object' ? d.account : null };
49
+ }
50
+ if (res.status === 428 || code === 'authorization_pending') {
51
+ // on continue
52
+ } else if (res.status === 429 || code === 'slow_down') {
53
+ wait += 5;
54
+ } else if (res.status === 410 || code === 'expired_token') {
55
+ throw new CloudError('The login code has expired: run "poad login" again.', { status: 410, code: 'expired_token', exit: EXIT.auth });
56
+ } else if (res.status === 403 || code === 'access_denied') {
57
+ throw new CloudError('The login was refused on poad.io: nothing saved.', { status: 403, code: 'access_denied', exit: EXIT.auth });
58
+ } else {
59
+ throw api.errorOf(res, 'login');
60
+ }
61
+ if (onWait) onWait(wait);
62
+ if (now() + wait * 1000 > deadline) throw new CloudError('The login code has expired: run "poad login" again.', { status: 410, code: 'expired_token', exit: EXIT.auth });
63
+ }
64
+ }
65
+
66
+ module.exports = { start, poll };
@@ -0,0 +1,45 @@
1
+ // Navigateur et presse-papiers de la machine, sans dépendance.
2
+ // Le texte copié passe par l'entrée standard de l'outil, jamais en argument
3
+ // (il serait visible dans la liste des processus).
4
+ const { spawn, spawnSync } = require('child_process');
5
+
6
+ /** Ouvre une adresse https dans le navigateur ; false si impossible */
7
+ function openBrowser(url) {
8
+ if (!/^https?:\/\//.test(String(url))) return false;
9
+ const cmd = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
10
+ try {
11
+ const child = spawn(cmd[0], cmd[1], { stdio: 'ignore', detached: true });
12
+ child.on('error', () => {});
13
+ child.unref();
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ }
19
+
20
+ const has = (bin) => {
21
+ const r = spawnSync(process.platform === 'win32' ? 'where' : 'which', [bin], { stdio: 'ignore' });
22
+ return r.status === 0;
23
+ };
24
+
25
+ /** Copie le texte dans le presse-papiers ; renvoie le nom de l'outil, ou null */
26
+ function copy(text) {
27
+ const tools =
28
+ process.platform === 'darwin'
29
+ ? [['pbcopy', []]]
30
+ : process.platform === 'win32'
31
+ ? [['clip', []]]
32
+ : [
33
+ ['wl-copy', []],
34
+ ['xclip', ['-selection', 'clipboard']],
35
+ ['xsel', ['--clipboard', '--input']],
36
+ ];
37
+ for (const [bin, args] of tools) {
38
+ if (!has(bin)) continue;
39
+ const r = spawnSync(bin, args, { input: text, stdio: ['pipe', 'ignore', 'ignore'], timeout: 5000 });
40
+ if (r.status === 0) return bin;
41
+ }
42
+ return null;
43
+ }
44
+
45
+ module.exports = { openBrowser, copy, has };
@@ -11,7 +11,7 @@ const sheets = {
11
11
  projects: {
12
12
  usage: ['poad projects [--json | --all | --scan | --prune [--yes]]', 'poad ls'],
13
13
  text: [
14
- 'The poad projects of this machine: name, state (running, stopped, not started, folder gone), engine version, console URL when running, last use and folder. The list comes from ~/.poad/projects.json, kept by poad init, create, start and upgrade; the state comes from one "docker ps -a". Nothing is started, stopped or deleted.',
14
+ 'The poad projects of this machine: name, state (running, stopped, not started, folder gone), engine version, console URL when running, poad.io project it is linked to, last use and folder. The list comes from ~/.poad/projects.json, kept by poad init, create, start and upgrade; the state comes from one "docker ps -a". Nothing is started, stopped or deleted.',
15
15
  ],
16
16
  options: [
17
17
  ['--json', 'the list as JSON, for a script'],
@@ -176,4 +176,125 @@ const alias = (of, name) => ({
176
176
  sheets.function = alias('functions', 'function');
177
177
  sheets.flow = alias('flows', 'flow');
178
178
 
179
+ // --- poad.io (projets hébergés) -------------------------------------------------
180
+ const EXIT_NOTE = 'Exit codes: 0 done, 1 error (poad.io, network), 2 usage (option, folder, link), 3 session (poad login), 4 confirmation missing or refused, 5 deploy failed.';
181
+ const API_NOTE = 'API: https://poad.io/_poad/cloud, or POAD_CLOUD_API. Session: POAD_ACCESS_TOKEN (CI) first, else the one saved by poad login.';
182
+ const PROJECT_OPT = ['--project <id>', 'a poad.io project other than the one linked to this folder'];
183
+ const JSON_OPT = ['--json', 'the result as JSON (errors too: { "error": { "code", "message" } })'];
184
+ Object.assign(sheets, {
185
+ login: {
186
+ usage: ['poad login [--no-browser] [--json]'],
187
+ text: [
188
+ 'Log this machine in to poad.io: a code is shown and its page opened in your browser; once you confirm it there, the session token is saved in ~/.poad/credentials.json (folder 0700, file 0600). The token is never shown nor written anywhere else.',
189
+ ],
190
+ options: [
191
+ ['--no-browser', 'show the address only (also without a terminal)'],
192
+ ['--json', 'the account as JSON (the code to confirm goes to stderr)'],
193
+ ],
194
+ notes: ['In CI, set POAD_ACCESS_TOKEN instead: it is used before the saved session.', API_NOTE, EXIT_NOTE],
195
+ },
196
+ logout: {
197
+ usage: ['poad logout [--json]'],
198
+ text: ['Forget the poad.io session of this machine (~/.poad/credentials.json). The token is not revoked by the CLI: revoke it on poad.io (account, CLI sessions) if it may have leaked.'],
199
+ options: [JSON_OPT],
200
+ },
201
+ whoami: { usage: ['poad whoami [--json]'], text: ['The poad.io account of the session, and where the session comes from (poad login or POAD_ACCESS_TOKEN).'], options: [JSON_OPT], notes: [EXIT_NOTE] },
202
+ cloud: {
203
+ usage: ['poad cloud <subcommand> [--json]'],
204
+ text: ['Projects hosted on poad.io. A local project is linked to one by [cloud] project = "<id>" in poad/config.toml (poad link, poad cloud create); then poad deploy, poad env, poad db url and poad db pull work on it.'],
205
+ notes: [API_NOTE, EXIT_NOTE],
206
+ },
207
+ 'cloud projects': { usage: ['poad cloud projects [--json]'], text: ['The poad.io projects of your account: id, name, state, engine, region; the one linked to this folder is marked.'], options: [JSON_OPT] },
208
+ 'cloud create': {
209
+ usage: ['poad cloud create [--name <name>] [--region paris] [--no-link] [--json]'],
210
+ text: ['Create a project on poad.io. In a poad project folder that is not linked yet, the folder is linked to it ([cloud] project in poad/config.toml).'],
211
+ options: [
212
+ ['--name <name>', 'its name (default: project_id of poad/config.toml, or the folder name)'],
213
+ ['--region <region>', 'its region (default: paris)'],
214
+ ['--no-link', 'do not link this folder'],
215
+ JSON_OPT,
216
+ ],
217
+ notes: [EXIT_NOTE],
218
+ },
219
+ 'cloud info': {
220
+ usage: ['poad cloud info [--project <id>] [--json]'],
221
+ text: ['The linked poad.io project: URL, anon key, state, engine version, region. The service_role key is never asked for nor shown.'],
222
+ options: [PROJECT_OPT, JSON_OPT],
223
+ },
224
+ 'cloud pause': { usage: ['poad cloud pause [--yes] [--project <id>] [--json]'], text: ['Pause the linked poad.io project: its API stops answering until poad cloud resume.'], options: [['--yes', 'no question (required outside a terminal)'], PROJECT_OPT, JSON_OPT], notes: [EXIT_NOTE] },
225
+ 'cloud resume': { usage: ['poad cloud resume [--project <id>] [--json]'], text: ['Resume the linked poad.io project.'], options: [PROJECT_OPT, JSON_OPT] },
226
+ 'cloud upgrade': {
227
+ usage: ['poad cloud upgrade [--to <version>] [--yes] [--project <id>] [--json]'],
228
+ text: ['Upgrade the engine of the linked poad.io project to the version poad.io offers (or --to). The project restarts.'],
229
+ options: [['--to <version>', 'a given version'], ['--yes', 'no question (required outside a terminal)'], PROJECT_OPT, JSON_OPT],
230
+ notes: [EXIT_NOTE],
231
+ },
232
+ link: {
233
+ usage: ['poad link [<id>] [--json]'],
234
+ text: [
235
+ 'Link this project to a poad.io project: writes [cloud] project = "<id>" in poad/config.toml. It holds no secret: commit it, so that the whole team deploys to the same project. Without <id>, choose in the list of your projects (in a terminal).',
236
+ ],
237
+ options: [JSON_OPT],
238
+ notes: ['poad projects shows the link of every project of this machine.', EXIT_NOTE],
239
+ },
240
+ unlink: { usage: ['poad unlink [--json]'], text: ['Remove [cloud] project from poad/config.toml. Nothing changes on poad.io.'], options: [JSON_OPT] },
241
+ env: {
242
+ usage: ['poad env ls', 'poad env create <name> [--kind persistent|preview]', 'poad env rm <name> [--yes]'],
243
+ text: [
244
+ 'Environments of the linked poad.io project: one branch each, with its own database and files; main is production. poad deploy, poad db url and poad db pull use the current git branch when an environment of that name exists, else main; --env <name> chooses.',
245
+ ],
246
+ options: [
247
+ ['ls', 'the environments (the default one is marked)'],
248
+ ['create <name>', 'a new environment; --kind persistent (default, kept) or preview (short-lived)'],
249
+ ['rm <name>', 'remove an environment with its database and files (asks first, --yes outside a terminal); main is never removed here'],
250
+ PROJECT_OPT,
251
+ JSON_OPT,
252
+ ],
253
+ notes: [EXIT_NOTE],
254
+ },
255
+ deploy: {
256
+ usage: ['poad deploy [--env <name>] [--dry-run] [--yes] [--json]'],
257
+ text: [
258
+ 'Send the poad/ folder to an environment of the linked poad.io project, which applies its pending migrations and loads its functions, flows, API, auth and storage settings.',
259
+ 'Sent: migrations, auth, storage, functions, flows, api, reference, variables (defaults, no secret), types, credentials/manifest.json (names and types only, never values), seed.sql, config.toml (without any secret key). Never sent: poad/secrets.toml, .env files, data/, backups/, node_modules, symbolic links. If a value of poad/secrets.toml appears in a file to send, nothing is sent.',
260
+ ],
261
+ options: [
262
+ ['--env <name>', 'the environment (default: the current git branch if it exists on poad.io, else main)'],
263
+ ['--dry-run', 'poad.io says what it would do (migrations to apply), nothing changes'],
264
+ ['--yes', 'no question for production (required outside a terminal)'],
265
+ PROJECT_OPT,
266
+ JSON_OPT,
267
+ ],
268
+ notes: [
269
+ 'Production (main): a summary, then a confirmation (none for --dry-run, which changes nothing). Uncommitted changes in poad/: a warning, and no commit id is sent (the commit id is sent when poad/ is clean).',
270
+ EXIT_NOTE,
271
+ ],
272
+ },
273
+ 'db url': {
274
+ usage: ['poad db url [--env <name>] [--mode session|transaction] [--show-password] [--copy | --no-copy] [--json]'],
275
+ text: [
276
+ 'Connection string of the database of the linked poad.io project: postgresql://postgres.<id>:<password>@db.poad.io:<port>/postgres?sslmode=require. The password is never printed unless --show-password: in a terminal, the full string goes to the clipboard and the screen shows it masked.',
277
+ ],
278
+ options: [
279
+ ['--mode session', 'port 5432, long connections (psql, pg_dump, migrations); the default'],
280
+ ['--mode transaction', 'port 6543, pooled short connections (serverless functions)'],
281
+ ['--show-password', 'print the full string (it stays in your terminal history)'],
282
+ ['--copy, --no-copy', 'copy to the clipboard even outside a terminal, or never'],
283
+ ['--env <name>', 'the environment (production only for now)'],
284
+ PROJECT_OPT,
285
+ JSON_OPT,
286
+ ],
287
+ notes: [EXIT_NOTE],
288
+ },
289
+ 'db pull': {
290
+ usage: ['poad db pull [--env <name>] [--name <name>] [--json]'],
291
+ text: [
292
+ 'Write the schema of the poad.io database into a new local migration (poad/migrations/<timestamp>_cloud_main_schema.sql), with pg_dump --schema-only through db.poad.io. Engine schemas (auth, storage, _poad…) are left out. An existing migration is never overwritten.',
293
+ 'pg_dump: the one of this machine, else the one of the local engine (project started), else the command tells what to install.',
294
+ ],
295
+ options: [['--name <name>', 'name of the migration'], ['--env <name>', 'the environment (production only for now)'], PROJECT_OPT, JSON_OPT],
296
+ notes: [EXIT_NOTE],
297
+ },
298
+ });
299
+
179
300
  module.exports = sheets;
package/utils/projects.js CHANGED
@@ -28,6 +28,7 @@ const file = (home) => path.join(dir(home), 'projects.json');
28
28
 
29
29
  const ID_RE = /^[A-Za-z0-9_.-]{1,80}$/;
30
30
  const VERSION_RE = /^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$/;
31
+ const CLOUD_RE = /^[a-z0-9][a-z0-9-]{2,62}$/;
31
32
 
32
33
  const empty = () => ({ version: VERSION, projects: {} });
33
34
 
@@ -44,6 +45,8 @@ function clean(e) {
44
45
  last_used_at: str(e.last_used_at, 40),
45
46
  engine: typeof e.engine === 'string' && VERSION_RE.test(e.engine) ? e.engine : null,
46
47
  template: str(e.template, 40),
48
+ // Projet poad.io lié ([cloud] project de poad/config.toml) : un identifiant, jamais un secret
49
+ cloud: typeof e.cloud === 'string' && CLOUD_RE.test(e.cloud) ? e.cloud : null,
47
50
  };
48
51
  }
49
52
 
@@ -152,6 +155,7 @@ function projectInfo(root) {
152
155
  name: typeof c.project_id === 'string' ? c.project_id : null,
153
156
  engine: typeof c.engine === 'string' ? c.engine : null,
154
157
  port: c.web && Number.isInteger(c.web.port) ? c.web.port : null,
158
+ cloud: c.cloud && typeof c.cloud.project === 'string' && CLOUD_RE.test(c.cloud.project) ? c.cloud.project : null,
155
159
  };
156
160
  } catch {
157
161
  return null;
@@ -185,15 +189,16 @@ function record(root, opts = {}) {
185
189
  const info = projectInfo(root);
186
190
  if (!info) return null;
187
191
  const now = new Date().toISOString();
188
- return update(
189
- (data) =>
190
- upsert(
191
- data,
192
- { id: info.id, name: info.name, path: projectPath(root), engine: info.engine, template: opts.template, last_used_at: opts.used ? now : undefined },
193
- now,
194
- ),
195
- opts.home,
196
- );
192
+ return update((data) => {
193
+ const e = upsert(
194
+ data,
195
+ { id: info.id, name: info.name, path: projectPath(root), engine: info.engine, template: opts.template, last_used_at: opts.used ? now : undefined },
196
+ now,
197
+ );
198
+ // La liaison suit config.toml, y compris quand elle est retirée (poad unlink)
199
+ if (e) e.cloud = info.cloud;
200
+ return e;
201
+ }, opts.home);
197
202
  } catch {
198
203
  return null;
199
204
  }
@@ -321,7 +326,8 @@ function rows(data, containers, { all = false } = {}) {
321
326
  const c = containers.find((x) => x.name === e.id);
322
327
  port = (info && info.port && hostPorts(c && c.ports).includes(info.port) ? info.port : null) || (info && info.port) || null;
323
328
  }
324
- return { ...e, name: (info && info.name) || e.name, engine, missing, state: missing ? 'missing' : state, port };
329
+ const cloud = info ? info.cloud : e.cloud || null;
330
+ return { ...e, name: (info && info.name) || e.name, engine, cloud, missing, state: missing ? 'missing' : state, port };
325
331
  });
326
332
  const order = { running: 0, stopped: 1, none: 2, unknown: 2, missing: 3 };
327
333
  return list