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.
- package/global/cli.js +14 -0
- package/global/cloud/action.js +37 -0
- package/global/cloud/create.js +42 -0
- package/global/cloud/index.js +19 -0
- package/global/cloud/info.js +37 -0
- package/global/cloud/pause.js +2 -0
- package/global/cloud/projects.js +32 -0
- package/global/cloud/resume.js +2 -0
- package/global/cloud/upgrade.js +2 -0
- package/global/create.js +4 -4
- package/global/init.js +2 -0
- package/global/login.js +32 -0
- package/global/logout.js +14 -0
- package/global/ls.js +2 -0
- package/global/projects.js +124 -0
- package/global/start.js +2 -0
- package/global/whoami.js +13 -0
- package/package.json +1 -1
- package/poad.js +5 -2
- package/project/cli.js +11 -0
- package/project/db/index.js +2 -0
- package/project/db/pull.js +92 -0
- package/project/db/url.js +33 -0
- package/project/deploy.js +136 -0
- package/project/env/create.js +19 -0
- package/project/env/index.js +2 -0
- package/project/env/ls.js +24 -0
- package/project/env/rm.js +21 -0
- package/project/link.js +38 -0
- package/project/unlink.js +12 -0
- package/project/upgrade.js +1 -0
- package/test/cloud.test.js +589 -0
- package/test/projects.test.js +167 -0
- package/utils/banner.js +3 -0
- package/utils/cloud/api.js +120 -0
- package/utils/cloud/branches.js +63 -0
- package/utils/cloud/bundle.js +226 -0
- package/utils/cloud/cli.js +166 -0
- package/utils/cloud/credentials.js +92 -0
- package/utils/cloud/db.js +34 -0
- package/utils/cloud/device.js +66 -0
- package/utils/cloud/system.js +45 -0
- package/utils/engine.js +1 -0
- package/utils/help-details.js +135 -0
- package/utils/projects.js +338 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
const test = require('node:test');
|
|
2
|
+
const assert = require('node:assert');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const reg = require('../utils/projects');
|
|
7
|
+
|
|
8
|
+
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'poad-reg-'));
|
|
9
|
+
|
|
10
|
+
/** Un projet poad minimal : <dir>/poad/config.toml, sans secret */
|
|
11
|
+
function project(base, name, uuid, engine = '0.38.0', port = 57111) {
|
|
12
|
+
const dir = path.join(base, name);
|
|
13
|
+
fs.mkdirSync(path.join(dir, 'poad', 'data'), { recursive: true });
|
|
14
|
+
fs.writeFileSync(path.join(dir, 'poad', 'config.toml'), `project_id = "${name}"\nproject_uuid = "${uuid}"\nengine = "${engine}"\n[web]\nport = ${port}\n`);
|
|
15
|
+
return path.join(dir, 'poad', 'config.toml');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
test('record writes a 0600 file in a 0700 folder, with no secret', () => {
|
|
19
|
+
const home = tmp();
|
|
20
|
+
const root = project(home, 'alpha', 'a1b2c3d4e5f6g7h8i9j0');
|
|
21
|
+
fs.writeFileSync(path.join(path.dirname(root), 'secrets.toml'), '[auth]\nsecret = "TOPSECRET"\n');
|
|
22
|
+
const e = reg.record(root, { home, template: 'next' });
|
|
23
|
+
assert.equal(e.id, 'a1b2c3d4e5f6g7h8i9j0');
|
|
24
|
+
assert.equal(e.name, 'alpha');
|
|
25
|
+
assert.equal(e.engine, '0.38.0');
|
|
26
|
+
assert.equal(e.template, 'next');
|
|
27
|
+
assert.equal(e.path, path.join(home, 'alpha'));
|
|
28
|
+
const f = reg.file(home);
|
|
29
|
+
assert.equal(fs.statSync(f).mode & 0o777, 0o600);
|
|
30
|
+
assert.equal(fs.statSync(reg.dir(home)).mode & 0o777, 0o700);
|
|
31
|
+
const text = fs.readFileSync(f, 'utf8');
|
|
32
|
+
assert.ok(!/TOPSECRET|secret|anon|service/i.test(text));
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test('record keeps created_at and template, refreshes engine and last_used_at', async () => {
|
|
36
|
+
const home = tmp();
|
|
37
|
+
const root = project(home, 'beta', 'bbbbbbbbbbbbbbbbbbbb', '0.37.0');
|
|
38
|
+
const first = reg.record(root, { home, template: 'angular' });
|
|
39
|
+
await new Promise((r) => setTimeout(r, 5));
|
|
40
|
+
fs.writeFileSync(root, fs.readFileSync(root, 'utf8').replace('0.37.0', '0.39.0'));
|
|
41
|
+
const second = reg.record(root, { home, used: true });
|
|
42
|
+
assert.equal(second.created_at, first.created_at);
|
|
43
|
+
assert.equal(second.template, 'angular');
|
|
44
|
+
assert.equal(second.engine, '0.39.0');
|
|
45
|
+
assert.ok(second.last_used_at);
|
|
46
|
+
assert.equal(Object.keys(reg.read(home).data.projects).length, 1);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test('record never throws (no config, unreadable config)', () => {
|
|
50
|
+
const home = tmp();
|
|
51
|
+
assert.equal(reg.record(path.join(home, 'nope', 'poad', 'config.toml'), { home }), null);
|
|
52
|
+
const root = project(home, 'gamma', 'cccccccccccccccccccc');
|
|
53
|
+
fs.writeFileSync(root, 'not = [toml');
|
|
54
|
+
assert.equal(reg.record(root, { home }), null);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test('a corrupt registry is kept aside and rebuilt', () => {
|
|
58
|
+
const home = tmp();
|
|
59
|
+
fs.mkdirSync(reg.dir(home), { recursive: true });
|
|
60
|
+
fs.writeFileSync(reg.file(home), '{ broken');
|
|
61
|
+
const r = reg.read(home);
|
|
62
|
+
assert.ok(r.corrupt && fs.existsSync(r.corrupt));
|
|
63
|
+
assert.deepEqual(r.data.projects, {});
|
|
64
|
+
const root = project(home, 'delta', 'dddddddddddddddddddd');
|
|
65
|
+
assert.ok(reg.record(root, { home }));
|
|
66
|
+
assert.equal(Object.keys(reg.read(home).data.projects).length, 1);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test('unknown fields and invalid entries never enter the registry', () => {
|
|
70
|
+
const home = tmp();
|
|
71
|
+
fs.mkdirSync(reg.dir(home), { recursive: true });
|
|
72
|
+
fs.writeFileSync(
|
|
73
|
+
reg.file(home),
|
|
74
|
+
JSON.stringify({ version: 1, projects: { x: { id: 'okokokokokokokokokok', path: '/tmp/x', anon_key: 'eyJ', engine: 'latest; rm' }, y: { id: '../bad', path: '/tmp/y' }, z: { id: 'zzz', path: 'relative' } } }),
|
|
75
|
+
);
|
|
76
|
+
const { data } = reg.read(home);
|
|
77
|
+
assert.deepEqual(Object.keys(data.projects), ['okokokokokokokokokok']);
|
|
78
|
+
assert.equal(data.projects.okokokokokokokokokok.anon_key, undefined);
|
|
79
|
+
assert.equal(data.projects.okokokokokokokokokok.engine, null);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('concurrent updates merge (lock): no entry lost', async () => {
|
|
83
|
+
const home = tmp();
|
|
84
|
+
const roots = Array.from({ length: 12 }, (_, i) => project(home, `p${i}`, `p${String(i).padStart(19, '0')}`));
|
|
85
|
+
// Processus séparés, lancés ensemble
|
|
86
|
+
const { spawn } = require('child_process');
|
|
87
|
+
const mod = require.resolve('../utils/projects');
|
|
88
|
+
await Promise.all(
|
|
89
|
+
roots.map(
|
|
90
|
+
(root) =>
|
|
91
|
+
new Promise((resolve, reject) => {
|
|
92
|
+
const p = spawn(process.execPath, ['-e', `require(${JSON.stringify(mod)}).record(${JSON.stringify(root)}, { home: ${JSON.stringify(home)} })`]);
|
|
93
|
+
p.on('exit', (c) => (c === 0 ? resolve() : reject(new Error('exit ' + c))));
|
|
94
|
+
}),
|
|
95
|
+
),
|
|
96
|
+
);
|
|
97
|
+
assert.equal(Object.keys(reg.read(home).data.projects).length, 12);
|
|
98
|
+
assert.ok(!fs.existsSync(reg.file(home) + '.lock'));
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
test('a stale lock is taken over', () => {
|
|
102
|
+
const home = tmp();
|
|
103
|
+
fs.mkdirSync(reg.file(home) + '.lock', { recursive: true });
|
|
104
|
+
const old = new Date(Date.now() - 60_000);
|
|
105
|
+
fs.utimesSync(reg.file(home) + '.lock', old, old);
|
|
106
|
+
assert.ok(reg.record(project(home, 'eps', 'eeeeeeeeeeeeeeeeeeee'), { home }));
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
test('remove (prune) drops only the given entries', () => {
|
|
110
|
+
const home = tmp();
|
|
111
|
+
reg.record(project(home, 'keep', 'kkkkkkkkkkkkkkkkkkkk'), { home });
|
|
112
|
+
reg.record(project(home, 'gone', 'gggggggggggggggggggg'), { home });
|
|
113
|
+
fs.rmSync(path.join(home, 'gone'), { recursive: true });
|
|
114
|
+
const { data } = reg.read(home);
|
|
115
|
+
const missing = reg.rows(data, [], { all: true }).filter((r) => r.missing);
|
|
116
|
+
assert.deepEqual(missing.map((r) => r.id), ['gggggggggggggggggggg']);
|
|
117
|
+
assert.equal(reg.rows(data, [], {}).length, 1);
|
|
118
|
+
assert.equal(reg.remove(missing.map((r) => r.id), home), 1);
|
|
119
|
+
assert.deepEqual(Object.keys(reg.read(home).data.projects), ['kkkkkkkkkkkkkkkkkkkk']);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test('docker ps parsing and project state', () => {
|
|
123
|
+
const ps = [
|
|
124
|
+
{ ID: '1', Names: 'aaaaaaaaaaaaaaaaaaaa', State: 'running', Image: 'poadio/engine:0.38.0', Ports: '127.0.0.1:57111->8000/tcp' },
|
|
125
|
+
{ ID: '2', Names: 'aaaaaaaaaaaaaaaaaaaa-mail', State: 'running', Image: 'axllent/mailpit', Ports: '' },
|
|
126
|
+
{ ID: '3', Names: 'bbbbbbbbbbbbbbbbbbbb', State: 'exited', Image: 'poadio/engine:0.37.0', Ports: '' },
|
|
127
|
+
{ ID: '4', Names: 'cccccccccccccccccccc-valkey', State: 'running', Image: 'valkey', Ports: '' },
|
|
128
|
+
]
|
|
129
|
+
.map((j) => JSON.stringify(j))
|
|
130
|
+
.join('\n');
|
|
131
|
+
const c = reg.parsePs(ps + '\nnot json\n');
|
|
132
|
+
assert.equal(c.length, 4);
|
|
133
|
+
assert.equal(reg.stateOf('aaaaaaaaaaaaaaaaaaaa', c), 'running');
|
|
134
|
+
assert.equal(reg.stateOf('bbbbbbbbbbbbbbbbbbbb', c), 'stopped');
|
|
135
|
+
assert.equal(reg.stateOf('cccccccccccccccccccc', c), 'stopped'); // annexe seule, engine absent
|
|
136
|
+
assert.equal(reg.stateOf('dddddddddddddddddddd', c), 'none');
|
|
137
|
+
assert.deepEqual(reg.hostPorts(c[0].ports), [57111]);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test('docker inspect parsing finds the project folder, engine wins over side services', () => {
|
|
141
|
+
const inspect = [
|
|
142
|
+
{ Name: '/qcz7dr23bzu1538sm8qb-valkey', Created: '2026-11-20T10:00:00Z', Config: { Image: 'valkey/valkey:8' }, Mounts: [{ Source: '/Users/me/prj/shop/poad/data/valkey', Destination: '/data' }] },
|
|
143
|
+
{ Name: '/qcz7dr23bzu1538sm8qb', Created: '2026-11-19T10:00:00Z', Config: { Image: 'poadio/engine:0.32.0' }, Mounts: [{ Source: '/Users/me/prj/shop/poad/data', Destination: '/data' }, { Source: '/Users/me/prj/shop/poad/functions', Destination: '/functions' }] },
|
|
144
|
+
{ Name: '/8usd0lgz1ziyoci9enbk-mail', Config: { Image: 'axllent/mailpit' }, Mounts: [{ Source: '/Users/me/prj/blog/poad/data/mail', Destination: '/data' }] },
|
|
145
|
+
{ Name: '/unrelated', Config: { Image: 'nginx' }, Mounts: [{ Source: '/srv/www', Destination: '/usr/share/nginx' }] },
|
|
146
|
+
];
|
|
147
|
+
const found = reg.parseInspect(inspect).sort((a, b) => a.path.localeCompare(b.path));
|
|
148
|
+
assert.deepEqual(found, [
|
|
149
|
+
{ id: '8usd0lgz1ziyoci9enbk', path: '/Users/me/prj/blog', engine: null, created_at: null },
|
|
150
|
+
{ id: 'qcz7dr23bzu1538sm8qb', path: '/Users/me/prj/shop', engine: '0.32.0', created_at: '2026-11-20T10:00:00Z' },
|
|
151
|
+
]);
|
|
152
|
+
assert.deepEqual(reg.parseInspect('garbage'), []);
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
test('rows: running first, console port from config, missing hidden unless all', () => {
|
|
156
|
+
const home = tmp();
|
|
157
|
+
reg.record(project(home, 'run', 'rrrrrrrrrrrrrrrrrrrr', '0.38.0', 57200), { home });
|
|
158
|
+
reg.record(project(home, 'idle', 'iiiiiiiiiiiiiiiiiiii'), { home });
|
|
159
|
+
const containers = reg.parsePs(JSON.stringify({ ID: '1', Names: 'rrrrrrrrrrrrrrrrrrrr', State: 'running', Image: 'poadio/engine:0.38.0', Ports: '127.0.0.1:57200->8000/tcp' }));
|
|
160
|
+
const r = reg.rows(reg.read(home).data, containers);
|
|
161
|
+
assert.equal(r[0].name, 'run');
|
|
162
|
+
assert.equal(r[0].state, 'running');
|
|
163
|
+
assert.equal(r[0].port, 57200);
|
|
164
|
+
assert.equal(r[1].state, 'none');
|
|
165
|
+
assert.equal(r[1].port, null);
|
|
166
|
+
assert.equal(reg.rows(reg.read(home).data, null)[1].state, 'unknown');
|
|
167
|
+
});
|
package/utils/banner.js
CHANGED
|
@@ -19,7 +19,9 @@ const SHORT = {
|
|
|
19
19
|
stop: 'Stop the project',
|
|
20
20
|
run: 'Run an optional service (kc, valkey, runner)',
|
|
21
21
|
ai: 'AI providers: keys of this machine, use in a project',
|
|
22
|
+
projects: 'The poad projects of this machine (also: poad ls)',
|
|
22
23
|
clean: 'Remove what stopped projects left on this machine',
|
|
24
|
+
login: 'Log in to poad.io (hosted projects: poad cloud)',
|
|
23
25
|
},
|
|
24
26
|
project: {
|
|
25
27
|
info: 'URLs, keys and state of the running project',
|
|
@@ -28,6 +30,7 @@ const SHORT = {
|
|
|
28
30
|
setup: 'Choose what poad start starts',
|
|
29
31
|
db: 'Local database: reset, seed, diff',
|
|
30
32
|
upgrade: 'Upgrade the engine of the project',
|
|
33
|
+
deploy: 'Send poad/ to its poad.io project (poad link)',
|
|
31
34
|
},
|
|
32
35
|
};
|
|
33
36
|
|
|
@@ -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 };
|