poad 2.63.0 → 2.64.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,169 @@
1
+ // poad storage cp : envoi en morceaux reprenables (utils/storage-tus.js), contre un faux Stockage TUS.
2
+ const test = require('node:test');
3
+ const assert = require('node:assert');
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const crypto = require('crypto');
8
+ const s = require('../utils/storage');
9
+ const c = require('../utils/storage-copy');
10
+ const t = require('../utils/storage-tus');
11
+
12
+ const ID = '0b8e8f7e-1b2c-4d5e-8f90-123456789abc';
13
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-tus-'));
14
+ process.env.POAD_UPLOADS_FILE = path.join(tmp, 'uploads.json');
15
+ test.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
16
+
17
+ /** Faux Stockage TUS : cut(n) → le n-ième PATCH n'en garde que la moitié et coupe la connexion */
18
+ function fakeTus({ cut = new Set(), tus = true, limit = Infinity } = {}) {
19
+ const uploads = new Map();
20
+ const objects = new Map();
21
+ const seen = [];
22
+ let patches = 0;
23
+ const doFetch = async (url, init = {}) => {
24
+ const route = new URL(url).pathname.replace('/storage/v1', '');
25
+ const h = init.headers || {};
26
+ seen.push({ method: init.method, route, headers: h });
27
+ const res = (status, headers = {}, body = null) => new Response(body, { status, headers });
28
+ if (route === '/upload/resumable' && init.method === 'POST') {
29
+ if (!tus) return res(404, {}, JSON.stringify({ error: 'NotFound', message: 'route inconnue' }));
30
+ if (Number(h['upload-length']) > limit) return res(413, {}, JSON.stringify({ error: 'EntityTooLarge', message: `taille maximale : ${limit} octets` }));
31
+ const meta = Object.fromEntries(h['upload-metadata'].split(',').map((p) => p.split(' ')).map(([k, v]) => [k, Buffer.from(v, 'base64').toString()]));
32
+ uploads.set(ID, { length: Number(h['upload-length']), got: Buffer.alloc(0), meta, upsert: h['x-upsert'] === 'true' });
33
+ return res(201, { location: `resumable/${ID}` });
34
+ }
35
+ const m = /^\/upload\/resumable\/(.+)$/.exec(route);
36
+ if (m) {
37
+ const u = uploads.get(m[1]);
38
+ if (!u) return res(404, {}, JSON.stringify({ message: 'envoi introuvable' }));
39
+ if (init.method === 'HEAD') return res(200, { 'upload-offset': String(u.got.length), 'upload-length': String(u.length) });
40
+ if (init.method === 'PATCH') {
41
+ patches++;
42
+ if (Number(h['upload-offset']) !== u.got.length) return res(409, { 'upload-offset': String(u.got.length) });
43
+ const body = Buffer.from(init.body);
44
+ if (cut.has(patches)) {
45
+ u.got = Buffer.concat([u.got, body.subarray(0, body.length >> 1)]);
46
+ throw new TypeError('fetch failed');
47
+ }
48
+ u.got = Buffer.concat([u.got, body]);
49
+ if (u.got.length === u.length) {
50
+ objects.set(`${u.meta.bucketName}/${u.meta.objectName}`, { body: u.got, type: u.meta.contentType });
51
+ uploads.delete(m[1]);
52
+ }
53
+ return res(204, { 'upload-offset': String(u.got.length) });
54
+ }
55
+ }
56
+ if (/^\/object\/list\//.test(route)) return res(200, {}, '[]');
57
+ const o = /^\/object\/(.+)$/.exec(route);
58
+ if (o && init.method === 'PUT') {
59
+ const chunks = [];
60
+ for await (const ch of init.body) chunks.push(Buffer.from(ch));
61
+ objects.set(o[1], { body: Buffer.concat(chunks), type: h['content-type'] });
62
+ return res(201, {}, '{}');
63
+ }
64
+ if (o && objects.has(o[1])) return res(200, { 'content-type': objects.get(o[1]).type }, objects.get(o[1]).body);
65
+ return res(404, {}, JSON.stringify({ message: 'route inconnue' }));
66
+ };
67
+ return { doFetch, seen, objects, uploads };
68
+ }
69
+
70
+ const bigFile = (name, size) => {
71
+ const file = path.join(tmp, name);
72
+ fs.writeFileSync(file, crypto.randomBytes(size));
73
+ return file;
74
+ };
75
+ const md5 = (b) => crypto.createHash('md5').update(b).digest('hex');
76
+ const noWait = async () => {};
77
+
78
+ test('metadata and resume key', () => {
79
+ assert.strictEqual(t.metadata({ bucket: 'docs', key: 'a.pdf', type: 'application/pdf' }), `bucketName ${Buffer.from('docs').toString('base64')},objectName ${Buffer.from('a.pdf').toString('base64')},contentType ${Buffer.from('application/pdf').toString('base64')}`);
80
+ assert.strictEqual(t.idOf(`resumable/${ID}`), ID);
81
+ assert.notStrictEqual(t.resumeKey({ base: 'a', bucket: 'b', key: 'c', size: 1, mtimeMs: 1 }), t.resumeKey({ base: 'a', bucket: 'b', key: 'c', size: 2, mtimeMs: 1 }));
82
+ });
83
+
84
+ test('cp: above 6 MiB, chunks of 6 MiB, content intact, nothing kept after', async () => {
85
+ const f = fakeTus();
86
+ const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
87
+ const file = bigFile('big.pdf', t.CHUNK * 2 + 77);
88
+ const { items } = await c.plan(api, file, 'poad:docs/');
89
+ const r = await c.run(api, items, {});
90
+ assert.strictEqual(r.errors.length, 0, r.errors.map((e) => e.error.message).join());
91
+ const patches = f.seen.filter((x) => x.method === 'PATCH');
92
+ assert.deepStrictEqual(patches.map((p) => Number(p.headers['content-length'])), [t.CHUNK, t.CHUNK, 77]);
93
+ assert.strictEqual(md5(f.objects.get('docs/big.pdf').body), md5(fs.readFileSync(file)));
94
+ assert.strictEqual(f.objects.get('docs/big.pdf').type, 'application/pdf');
95
+ assert.strictEqual(items[0].chunked, true);
96
+ assert.deepStrictEqual(t.readState(), {});
97
+ // Jamais la clé dans une URL ni dans le fichier de reprise
98
+ assert.ok(f.seen.every((x) => !x.route.includes('k=') && x.headers.authorization === 'Bearer k'));
99
+ });
100
+
101
+ test('cp: connection cut in the middle of a chunk → HEAD, resumed at the right offset', async () => {
102
+ const f = fakeTus({ cut: new Set([2]) });
103
+ const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
104
+ const file = bigFile('cut.bin', t.CHUNK * 3);
105
+ const resumed = [];
106
+ await t.tusUpload(api, t.fileSource(file, t.CHUNK * 3), { bucket: 'docs', key: 'cut.bin', base: 'http://x', mtimeMs: 1, onResume: (o) => resumed.push(o), sleep: noWait });
107
+ assert.deepStrictEqual(resumed, [t.CHUNK + t.CHUNK / 2]);
108
+ assert.strictEqual(md5(f.objects.get('docs/cut.bin').body), md5(fs.readFileSync(file)));
109
+ });
110
+
111
+ test('cp: command interrupted, run again → resumed where the server is, no new upload', async () => {
112
+ const cut = new Set([2, 3, 4, 5, 6, 7, 8, 9]);
113
+ const f = fakeTus({ cut });
114
+ const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
115
+ const file = bigFile('again.bin', t.CHUNK * 3);
116
+ const st = fs.statSync(file);
117
+ const opts = { bucket: 'docs', key: 'again.bin', base: 'http://x', mtimeMs: st.mtimeMs, sleep: noWait };
118
+ await assert.rejects(t.tusUpload(api, t.fileSource(file, st.size), opts), /connection lost/);
119
+ assert.strictEqual(Object.keys(t.readState()).length, 1);
120
+ assert.ok(!fs.readFileSync(process.env.POAD_UPLOADS_FILE, 'utf8').includes('Bearer'));
121
+ cut.clear();
122
+ const r = await t.tusUpload(api, t.fileSource(file, st.size), opts);
123
+ assert.ok(r.resumedFrom > t.CHUNK);
124
+ assert.strictEqual(f.seen.filter((x) => x.method === 'POST').length, 1);
125
+ assert.strictEqual(md5(f.objects.get('docs/again.bin').body), md5(fs.readFileSync(file)));
126
+ });
127
+
128
+ test('cp: refused before any byte when the announced size is above the limit', async () => {
129
+ const f = fakeTus({ limit: 1000 });
130
+ const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
131
+ const file = bigFile('huge.bin', t.CHUNK + 1);
132
+ const { items } = await c.plan(api, file, 'poad:docs/');
133
+ const r = await c.run(api, items, {});
134
+ assert.strictEqual(r.errors.length, 1);
135
+ assert.match(s.reason(r.errors[0].error), /at most 1000 bytes/);
136
+ assert.strictEqual(f.seen.filter((x) => x.method === 'PATCH').length, 0);
137
+ });
138
+
139
+ test('cp: an engine without chunked uploads → one request, as before', async () => {
140
+ const f = fakeTus({ tus: false });
141
+ const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
142
+ const file = bigFile('old.bin', t.CHUNK + 5);
143
+ const { items } = await c.plan(api, file, 'poad:docs/');
144
+ const r = await c.run(api, items, {});
145
+ assert.strictEqual(r.errors.length, 0);
146
+ assert.ok(f.seen.some((x) => x.method === 'PUT'));
147
+ assert.strictEqual(api.noTus, true);
148
+ assert.strictEqual(f.objects.get('docs/old.bin').body.length, t.CHUNK + 5);
149
+ });
150
+
151
+ test('cp: storage → storage above 6 MiB, read from the stream in chunks', async () => {
152
+ const f = fakeTus();
153
+ const data = crypto.randomBytes(t.CHUNK * 2 + 9);
154
+ f.objects.set('src/a.bin', { body: data, type: 'application/octet-stream' });
155
+ const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
156
+ await c.transfer(api, { from: { bucket: 'src', key: 'a.bin' }, to: { bucket: 'dst', key: 'a.bin' }, size: data.length, type: 'application/octet-stream' });
157
+ assert.strictEqual(md5(f.objects.get('dst/a.bin').body), md5(data));
158
+ });
159
+
160
+ test('[storage] file_size_limit of config.toml → POAD_STORAGE_FILE_SIZE_LIMIT in bytes', () => {
161
+ assert.deepStrictEqual(s.engineEnv({ storage: { file_size_limit: '200MB' } }), ['POAD_STORAGE_FILE_SIZE_LIMIT=200000000']);
162
+ assert.deepStrictEqual(s.engineEnv({ storage: { file_size_limit: '1GiB' } }), ['POAD_STORAGE_FILE_SIZE_LIMIT=1073741824']);
163
+ assert.deepStrictEqual(s.engineEnv({ storage: { file_size_limit: 52428800 } }), ['POAD_STORAGE_FILE_SIZE_LIMIT=52428800']);
164
+ assert.deepStrictEqual(s.engineEnv({}), []);
165
+ const bad = s.fileSizeLimit({ storage: { file_size_limit: 'beaucoup' } });
166
+ assert.strictEqual(bad.value, null);
167
+ assert.match(bad.warning, /not a size/);
168
+ assert.deepStrictEqual(s.engineEnv({ storage: { file_size_limit: 'beaucoup' } }), []);
169
+ });
@@ -150,6 +150,13 @@ test('plan and run: storage → storage keeps the base name and the original typ
150
150
  assert.strictEqual(one.items[0].to.key, 'z.png');
151
151
  // Copie dans elle-même refusée
152
152
  await assert.rejects(c.plan(api, 'poad:img/2024', 'poad:img/2024/', { recursive: true }), /inside/);
153
+ // Vers la racine du bucket qui la contient déjà : son contenu monte d'un cran (plus de refus « is inside »)
154
+ const up = await c.plan(api, 'poad:img/2024', 'poad:img', { recursive: true });
155
+ assert.deepStrictEqual(up.items.map((i) => i.to.key).sort(), ['b.png', 'sub/c.png']);
156
+ const up2 = await c.plan(api, 'poad:img/2024/sub', 'poad:img/2024/', { recursive: true });
157
+ assert.deepStrictEqual(up2.items.map((i) => i.to.key), ['2024/c.png']);
158
+ // La racine entière dans un de ses dossiers : toujours refusé
159
+ await assert.rejects(c.plan(api, 'poad:img/', 'poad:img/2024/', { recursive: true }), /inside/);
153
160
  // Les deux chemins sur le disque : refusé
154
161
  await assert.rejects(c.plan(api, 'a', 'b'), /must be in the storage/);
155
162
  });
@@ -0,0 +1,204 @@
1
+ // poad auth import <fichier> : lecture du fichier de comptes (JSON, JSON Lines,
2
+ // CSV), découpage en lots, envoi au service auth (POST /auth/v1/admin/users/import),
3
+ // bilan. La vérification de chaque ligne (empreinte bcrypt, adresse, dates…)
4
+ // est faite par le service auth, la même que dans la console.
5
+ //
6
+ // Jamais d'empreinte ni de mot de passe dans un message : les erreurs de
7
+ // lecture ne reprennent pas le texte du fichier, et le service n'en renvoie pas.
8
+ const { CloudError, usageError } = require('./cloud/api');
9
+
10
+ /** Lignes par requête (le service en accepte 1000) */
11
+ const BATCH = 500;
12
+
13
+ const parseJson = (text, line) => {
14
+ try {
15
+ return JSON.parse(text);
16
+ } catch {
17
+ // Le message de JSON.parse cite le texte : il peut contenir une empreinte
18
+ throw usageError(line ? `Invalid JSON on line ${line}.` : 'Invalid JSON.');
19
+ }
20
+ };
21
+
22
+ /** CSV (RFC 4180) : guillemets, guillemets doublés, retours à la ligne dans un champ ; virgule ou point-virgule */
23
+ function parseCsv(text) {
24
+ const src = text.replace(/^/, '');
25
+ const first = src.split(/\r?\n/, 1)[0] || '';
26
+ const sep = (first.match(/;/g) || []).length > (first.match(/,/g) || []).length ? ';' : ',';
27
+ const out = [];
28
+ let cells = [];
29
+ let cell = '';
30
+ let quoted = false;
31
+ let line = 1;
32
+ let start = 1;
33
+ for (let i = 0; i < src.length; i++) {
34
+ const c = src[i];
35
+ if (quoted) {
36
+ if (c === '"' && src[i + 1] === '"') {
37
+ cell += '"';
38
+ i++;
39
+ } else if (c === '"') quoted = false;
40
+ else {
41
+ if (c === '\n') line++;
42
+ cell += c;
43
+ }
44
+ } else if (c === '"' && cell === '') quoted = true;
45
+ else if (c === sep) {
46
+ cells.push(cell);
47
+ cell = '';
48
+ } else if (c === '\n' || c === '\r') {
49
+ if (c === '\r' && src[i + 1] === '\n') i++;
50
+ cells.push(cell);
51
+ if (cells.some((x) => x !== '')) out.push({ line: start, cells });
52
+ cells = [];
53
+ cell = '';
54
+ line++;
55
+ start = line;
56
+ } else cell += c;
57
+ }
58
+ if (quoted) throw usageError(`Invalid CSV: a quote opened on line ${start} is never closed.`);
59
+ cells.push(cell);
60
+ if (cells.some((x) => x !== '')) out.push({ line: start, cells });
61
+ const [head, ...records] = out;
62
+ return { header: ((head && head.cells) || []).map((h) => h.trim()), records };
63
+ }
64
+
65
+ /**
66
+ * Le contenu d'un fichier en comptes : { rows, lines, format }. Format choisi
67
+ * par l'extension (.json, .jsonl/.ndjson, .csv), sinon par le contenu.
68
+ */
69
+ function parseFile(name, text) {
70
+ const trimmed = String(text).replace(/^/, '').trim();
71
+ if (!trimmed) throw usageError('The file is empty.');
72
+ const lower = String(name).toLowerCase();
73
+ if (lower.endsWith('.jsonl') || lower.endsWith('.ndjson')) {
74
+ const rows = [];
75
+ const lines = [];
76
+ trimmed.split(/\r?\n/).forEach((l, i) => {
77
+ if (!l.trim()) return;
78
+ rows.push(parseJson(l, i + 1));
79
+ lines.push(i + 1);
80
+ });
81
+ return { rows, lines, format: 'jsonl' };
82
+ }
83
+ if (lower.endsWith('.json') || /^[[{]/.test(trimmed)) {
84
+ const data = parseJson(trimmed);
85
+ const list = Array.isArray(data) ? data : data && Array.isArray(data.users) ? data.users : null;
86
+ if (!list) throw usageError('JSON expected: a list of accounts, or an object { "users": [...] }.');
87
+ return { rows: list, lines: list.map((_, i) => i + 1), format: 'json' };
88
+ }
89
+ const { header, records } = parseCsv(trimmed);
90
+ if (!header.includes('email')) throw usageError('CSV expected: a first header line with at least an "email" column.');
91
+ return {
92
+ rows: records.map(({ cells }) => Object.fromEntries(header.map((h, i) => [h, cells[i] === undefined ? '' : cells[i]]).filter(([h, v]) => h && v !== ''))),
93
+ lines: records.map((r) => r.line),
94
+ format: 'csv',
95
+ };
96
+ }
97
+
98
+ const emailOf = (row) => (row && typeof row === 'object' ? String(row.email == null ? '' : row.email).trim().toLowerCase() : '');
99
+
100
+ /** Doublons sur tout le fichier (le service ne voit qu'un lot) : la première ligne compte */
101
+ function splitDuplicates({ rows, lines }) {
102
+ const seen = new Set();
103
+ const keep = [];
104
+ const duplicates = [];
105
+ rows.forEach((row, i) => {
106
+ const email = emailOf(row);
107
+ if (email && seen.has(email)) duplicates.push({ line: lines[i], email, status: 'invalid', reason: 'duplicate email in the file' });
108
+ else {
109
+ if (email) seen.add(email);
110
+ keep.push({ row, line: lines[i] });
111
+ }
112
+ });
113
+ return { keep, duplicates };
114
+ }
115
+
116
+ function batches(items, size = BATCH) {
117
+ const out = [];
118
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
119
+ return out;
120
+ }
121
+
122
+ function summarize(results) {
123
+ const s = { total: results.length, created: 0, would_create: 0, exists: 0, invalid: 0, failed: 0, verified: 0, verified_ignored: 0, confirmations_sent: 0, confirmations_failed: 0, confirmations_to_send: 0 };
124
+ for (const r of results) {
125
+ s[r.status] += 1;
126
+ if (r.verified_ignored) s.verified_ignored += 1;
127
+ if (r.confirmation === 'sent') s.confirmations_sent += 1;
128
+ if (r.confirmation === 'failed') s.confirmations_failed += 1;
129
+ if (r.confirmation === 'would_send') s.confirmations_to_send += 1;
130
+ if ((r.status === 'created' || r.status === 'would_create') && r.email_verified) s.verified += 1;
131
+ }
132
+ return s;
133
+ }
134
+
135
+ /**
136
+ * Appel du service auth de la cible (local : clé service_role ; poad.io : jeton
137
+ * court renouvelé une minute avant son expiration, comme poad storage).
138
+ */
139
+ function authClient({ base, key, apikey, renew }, { fetch: doFetch = fetch, timeout = 120000 } = {}) {
140
+ let auth = { key, apikey: apikey || key, expires: renew && renew.first ? Date.parse(renew.first) : null };
141
+ return async function importBatch(body) {
142
+ if (renew && auth.expires && auth.expires - Date.now() < 60000) {
143
+ const t = await renew.next();
144
+ auth = { key: t.token, apikey: t.anon_key, expires: Date.parse(t.expires_at) };
145
+ }
146
+ let res;
147
+ try {
148
+ res = await doFetch(`${base}/auth/v1/admin/users/import`, {
149
+ method: 'POST',
150
+ headers: { apikey: auth.apikey, authorization: `Bearer ${auth.key}`, 'content-type': 'application/json' },
151
+ body: JSON.stringify(body),
152
+ signal: AbortSignal.timeout(timeout),
153
+ });
154
+ } catch (err) {
155
+ throw new CloudError(`The auth service does not answer on ${base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
156
+ }
157
+ const text = await res.text().catch(() => '');
158
+ let data = null;
159
+ try {
160
+ data = text ? JSON.parse(text) : null;
161
+ } catch {
162
+ data = null;
163
+ }
164
+ if (res.status === 404) throw new CloudError('This engine does not know the import of accounts (auth 0.13.0 or later needed): run "poad upgrade".', { status: 404, code: 'unsupported' });
165
+ if (res.status < 200 || res.status >= 300) {
166
+ const msg = (data && (data.msg || data.message || data.error_description)) || `HTTP ${res.status}`;
167
+ throw new CloudError(`The auth service refused the import: ${msg}`, { status: res.status, code: (data && data.error_code) || `http_${res.status}` });
168
+ }
169
+ return data;
170
+ };
171
+ }
172
+
173
+ /**
174
+ * Examine (dryRun) ou importe le fichier lot par lot. onBatch(done, total)
175
+ * suit l'avancement. Un lot refusé (réseau, droits) marque ses lignes en
176
+ * échec et arrête l'import : relancer reprend sans doublon.
177
+ */
178
+ async function run(parsed, { send, dryRun = false, trustVerified = false, sendConfirmation = false, onBatch = () => {} }) {
179
+ const { keep, duplicates } = splitDuplicates(parsed);
180
+ const results = [...duplicates];
181
+ let done = 0;
182
+ let stopped = null;
183
+ for (const batch of batches(keep)) {
184
+ if (stopped) {
185
+ for (const b of batch) results.push({ line: b.line, email: emailOf(b.row), status: 'failed', reason: `not sent: ${stopped}` });
186
+ continue;
187
+ }
188
+ try {
189
+ const out = await send({ users: batch.map((b) => b.row), dry_run: dryRun, trust_verified: trustVerified, send_confirmation: sendConfirmation });
190
+ for (const x of out.results)
191
+ results.push({ line: batch[x.index].line, email: x.email, status: x.status, reason: x.reason, email_verified: x.email_verified, has_password: x.has_password, id: x.id, verified_ignored: x.verified_ignored, confirmation: x.confirmation });
192
+ } catch (err) {
193
+ if (err && err.code === 'unsupported') throw err;
194
+ stopped = err && err.message ? err.message : String(err);
195
+ for (const b of batch) results.push({ line: b.line, email: emailOf(b.row), status: 'failed', reason: stopped });
196
+ }
197
+ done += batch.length;
198
+ onBatch(done, keep.length);
199
+ }
200
+ results.sort((a, b) => a.line - b.line);
201
+ return { results, summary: summarize(results) };
202
+ }
203
+
204
+ module.exports = { BATCH, parseCsv, parseFile, splitDuplicates, batches, summarize, authClient, run };
@@ -194,7 +194,11 @@ function build(poadDir, { limits = LIMITS, exclude = [] } = {}) {
194
194
  } catch {}
195
195
  }
196
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`);
197
+ // Dépendances npm des fonctions : seuls les fichiers que leurs imports atteignent (utils/cloud/deps.js)
198
+ const deps = require('./deps').traceDependencies(path.join(poadDir, 'functions'));
199
+ const depFiles = deps.files.map((f) => ({ ...f, path: `functions/${f.rel}` }));
200
+ for (const s of skipped) if (s.path === 'functions/node_modules/') s.reason = depFiles.length ? `only the ${depFiles.length} file(s) the functions import are sent` : 'nothing imported by the functions';
201
+ if (rels.length + depFiles.length > limits.maxEntries) throw new BundleError(`more than ${limits.maxEntries} files to send`);
198
202
 
199
203
  const secrets = localSecrets(poadDir);
200
204
  const files = [];
@@ -232,9 +236,19 @@ function build(poadDir, { limits = LIMITS, exclude = [] } = {}) {
232
236
  if (total > limits.maxBytes) throw new BundleError(`the poad/ folder to send is larger than ${limits.maxBytes} bytes`);
233
237
  files.push({ path: rel, data, mode: st.mode & 0o111 ? 0o755 : 0o644 });
234
238
  }
239
+ for (const f of depFiles) {
240
+ const st = fs.statSync(f.abs);
241
+ if (st.size > limits.maxFile) throw new BundleError(`${f.path} is larger than ${Math.round(limits.maxFile / 1048576)} MB`);
242
+ const data = f.data || fs.readFileSync(f.abs);
243
+ for (const s of secrets) if (data.includes(s)) throw new BundleError(`${f.path} contains a secret of poad/secrets.toml: nothing was sent.`);
244
+ total += data.length;
245
+ if (total > limits.maxBytes) throw new BundleError(`the poad/ folder to send is larger than ${limits.maxBytes} bytes`);
246
+ // Jamais exécutable : un paquet n'apporte que du code et des données lus par l'engine
247
+ files.push({ path: f.path, data, mode: 0o644 });
248
+ }
235
249
  files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
236
250
  const tgz = zlib.gzipSync(tar(files), { level: 9 });
237
- return { tgz, files: files.map((f) => ({ path: f.path, size: f.data.length })), skipped, bytes: total };
251
+ return { tgz, files: files.map((f) => ({ path: f.path, size: f.data.length })), skipped, bytes: total, deps: { packages: deps.packages, files: depFiles.length, missing: deps.missing, outside: deps.outside } };
238
252
  }
239
253
 
240
254
  module.exports = { build, tar, cleanConfig, cleanCredentialsManifest, localSecrets, BundleError, DIRS, FILES, LIMITS };