poad 2.61.2 → 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
+ });
@@ -5,6 +5,8 @@ const os = require('os');
5
5
  const path = require('path');
6
6
  const s = require('../utils/storage');
7
7
  const c = require('../utils/storage-copy');
8
+ const crypto = require('crypto');
9
+ const md5 = (b) => crypto.createHash('md5').update(b).digest('hex');
8
10
 
9
11
  test('parseRemote: bucket, key, folder', () => {
10
12
  assert.deepStrictEqual(s.parseRemote('poad:images/a/b.png'), { bucket: 'images', key: 'a/b.png', dir: false });
@@ -39,7 +41,8 @@ test('entries: folders first with count and size, then files', () => {
39
41
  });
40
42
 
41
43
  // Faux Stockage en mémoire, derrière un fetch : les routes que le CLI appelle
42
- function fakeStorage(initial = {}) {
44
+ // folders : le service connaît la vue d'un dossier (storage 0.5+ : { prefix, delimiter: "/" })
45
+ function fakeStorage(initial = {}, { limit = Infinity, folders = false } = {}) {
43
46
  const objects = new Map(Object.entries(initial));
44
47
  const seen = [];
45
48
  const doFetch = async (url, init = {}) => {
@@ -49,12 +52,30 @@ function fakeStorage(initial = {}) {
49
52
  const json = (status, body) => new Response(body === undefined ? null : JSON.stringify(body), { status });
50
53
  let m;
51
54
  if ((m = /^\/object\/list\/([^/]+)$/.exec(route))) {
52
- const { prefix, limit, offset } = JSON.parse(init.body);
55
+ const { prefix, limit, offset, delimiter } = JSON.parse(init.body);
56
+ if (folders && delimiter === '/') {
57
+ const under = [...objects.keys()].filter((k) => k.startsWith(`${m[1]}/${prefix}`)).sort().map((k) => k.slice(m[1].length + 1));
58
+ const view = new Map();
59
+ const direct = [];
60
+ for (const name of under) {
61
+ const rest = name.slice(prefix.length);
62
+ const cut = rest.indexOf('/');
63
+ if (cut < 0) direct.push(name);
64
+ else {
65
+ const f = view.get(rest.slice(0, cut)) || { name: rest.slice(0, cut), files: 0, size: 0, updated_at: '2026-12-01T10:00:00Z' };
66
+ f.files++;
67
+ f.size += objects.get(`${m[1]}/${name}`).body.length;
68
+ view.set(f.name, f);
69
+ }
70
+ }
71
+ const meta = (name) => ({ size: objects.get(`${m[1]}/${name}`).body.length, mimetype: objects.get(`${m[1]}/${name}`).type });
72
+ return json(200, { prefix, folders: [...view.values()], files: direct.slice(offset, offset + limit).map((name) => ({ name, metadata: meta(name), updated_at: '2026-12-01T10:00:00Z' })), total_files: direct.length });
73
+ }
53
74
  const rows = [...objects.keys()]
54
75
  .filter((k) => k.startsWith(`${m[1]}/${prefix}`))
55
76
  .sort()
56
77
  .slice(offset, offset + limit)
57
- .map((k) => ({ name: k.slice(m[1].length + 1), metadata: { size: objects.get(k).body.length, mimetype: objects.get(k).type }, updated_at: '2026-12-01T10:00:00Z' }));
78
+ .map((k) => ({ name: k.slice(m[1].length + 1), metadata: { size: objects.get(k).body.length, mimetype: objects.get(k).type, etag: md5(objects.get(k).body) }, updated_at: '2026-12-01T10:00:00Z' }));
58
79
  return json(200, rows);
59
80
  }
60
81
  if ((m = /^\/object\/([^/]+)$/.exec(route)) && init.method === 'DELETE') {
@@ -64,9 +85,14 @@ function fakeStorage(initial = {}) {
64
85
  }
65
86
  if ((m = /^\/object\/(.+)$/.exec(route))) {
66
87
  if (init.method === 'PUT') {
88
+ seen.push({ put: m[1] });
89
+ // Comme le storage : la taille annoncée, puis la taille reçue
90
+ if (Number(init.headers['content-length']) > limit) return json(413, { statusCode: '413', error: 'EntityTooLarge', message: `taille maximale : ${limit} octets` });
67
91
  const chunks = [];
68
92
  for await (const ch of init.body) chunks.push(Buffer.from(ch));
69
- objects.set(m[1], { body: Buffer.concat(chunks), type: init.headers['content-type'] });
93
+ const body = Buffer.concat(chunks);
94
+ if (body.length > limit) return json(413, { statusCode: '413', error: 'EntityTooLarge', message: `taille maximale : ${limit} octets` });
95
+ objects.set(m[1], { body, type: init.headers['content-type'] });
70
96
  return json(201, { name: m[1] });
71
97
  }
72
98
  const o = objects.get(m[1]);
@@ -124,6 +150,13 @@ test('plan and run: storage → storage keeps the base name and the original typ
124
150
  assert.strictEqual(one.items[0].to.key, 'z.png');
125
151
  // Copie dans elle-même refusée
126
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/);
127
160
  // Les deux chemins sur le disque : refusé
128
161
  await assert.rejects(c.plan(api, 'a', 'b'), /must be in the storage/);
129
162
  });
@@ -184,3 +217,206 @@ test('client: hosted, anon key for the gateway, storage token renewed before it
184
217
  test('target: --env or --project goes to poad.io, else the local engine', async () => {
185
218
  await assert.rejects(s.target({}, { started: async () => true }), /not in a poad project|service_role|started/);
186
219
  });
220
+
221
+ test('concurrency: 1 to 32, default 4, anything else is a usage error', () => {
222
+ assert.strictEqual(s.concurrency(undefined), 4);
223
+ assert.strictEqual(s.concurrency('1'), 1);
224
+ assert.strictEqual(s.concurrency('32'), 32);
225
+ for (const bad of ['0', '33', '-2', '2.5', 'x', ''])
226
+ assert.throws(() => s.concurrency(bad), (e) => e.code === 'usage' && /1 to 32/.test(e.message));
227
+ });
228
+
229
+ test('each: never more than the concurrency asked at once', async () => {
230
+ let now = 0;
231
+ let max = 0;
232
+ await s.each(Array.from({ length: 20 }, (_, i) => i), async () => {
233
+ max = Math.max(max, ++now);
234
+ await new Promise((r) => setTimeout(r, 2));
235
+ now--;
236
+ }, 7);
237
+ assert.strictEqual(max, 7);
238
+ });
239
+
240
+ test('reason: the size limit of the storage, readable', () => {
241
+ const { CloudError } = require('../utils/cloud/api');
242
+ assert.strictEqual(s.reason(new CloudError('taille maximale : 52428800 octets', { status: 413 })), 'too large: the storage accepts at most 52428800 bytes (50 MB) per file');
243
+ assert.strictEqual(s.reason(new CloudError('HTTP 413', { status: 413 })), 'too large for the storage (HTTP 413)');
244
+ assert.strictEqual(s.reason(new Error('bucket introuvable')), 'bucket introuvable');
245
+ });
246
+
247
+ test('commonDir: one list per destination folder', () => {
248
+ assert.strictEqual(c.commonDir(['a/b/c.png']), 'a/b/c.png');
249
+ assert.strictEqual(c.commonDir(['site/a.html', 'site/css/s.css']), 'site/');
250
+ assert.strictEqual(c.commonDir(['site/a', 'sitemap']), '');
251
+ });
252
+
253
+ // Un dossier du disque : 3 petits fichiers et un trop gros pour le faux Stockage (limite 10 octets)
254
+ function tree() {
255
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-storage-'));
256
+ fs.mkdirSync(path.join(dir, 'site', 'img'), { recursive: true });
257
+ fs.writeFileSync(path.join(dir, 'site', 'a.txt'), 'A');
258
+ fs.writeFileSync(path.join(dir, 'site', 'b.txt'), 'BB');
259
+ fs.writeFileSync(path.join(dir, 'site', 'img', 'big.bin'), Buffer.alloc(64));
260
+ fs.writeFileSync(path.join(dir, 'site', 'img', 'c.txt'), 'CCC');
261
+ return dir;
262
+ }
263
+
264
+ test('run: a failure does not stop the others; failures list path and reason', async () => {
265
+ const f = fakeStorage({}, { limit: 10 });
266
+ const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
267
+ const dir = tree();
268
+ try {
269
+ const { items } = await c.plan(api, path.join(dir, 'site'), 'poad:web/', { recursive: true });
270
+ const seen = [];
271
+ const r = await c.run(api, items, { concurrency: 2, onError: (it, e) => seen.push([c.label(it.from), e.status]) });
272
+ assert.strictEqual(r.done.length, 3);
273
+ assert.strictEqual(r.errors.length, 1);
274
+ assert.deepStrictEqual(seen, [[path.relative(process.cwd(), path.join(dir, 'site', 'img', 'big.bin')).startsWith('..') ? path.join(dir, 'site', 'img', 'big.bin') : path.relative(process.cwd(), path.join(dir, 'site', 'img', 'big.bin')), 413]]);
275
+ const list = c.failures(r.errors);
276
+ assert.strictEqual(list.length, 1);
277
+ assert.ok(list[0].path.endsWith(path.join('site', 'img', 'big.bin')));
278
+ assert.strictEqual(list[0].to, 'web/site/img/big.bin');
279
+ assert.strictEqual(list[0].reason, 'too large: the storage accepts at most 10 bytes (10 B) per file');
280
+ // La taille connue part dans l'en-tête : refus avant l'envoi du contenu
281
+ assert.ok(!f.objects.has('web/site/img/big.bin'));
282
+ } finally {
283
+ fs.rmSync(dir, { recursive: true, force: true });
284
+ }
285
+ });
286
+
287
+ test('run again: an identical file at the destination is not copied again (disk → storage, storage → disk, storage → storage)', async () => {
288
+ const f = fakeStorage();
289
+ const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
290
+ const dir = tree();
291
+ const puts = () => f.seen.filter((x) => x.put).map((x) => x.put).sort();
292
+ try {
293
+ // Disque → Stockage, deux fois : la seconde n'envoie que le fichier changé et le nouveau
294
+ let r = await c.run(api, (await c.plan(api, path.join(dir, 'site'), 'poad:web/', { recursive: true })).items);
295
+ assert.deepStrictEqual([r.done.length, r.unchanged.length], [4, 0]);
296
+ f.seen.length = 0;
297
+ fs.writeFileSync(path.join(dir, 'site', 'b.txt'), 'bb'); // même taille, autre contenu
298
+ fs.writeFileSync(path.join(dir, 'site', 'd.txt'), 'D');
299
+ r = await c.run(api, (await c.plan(api, path.join(dir, 'site'), 'poad:web/', { recursive: true })).items);
300
+ assert.deepStrictEqual(puts(), ['web/site/b.txt', 'web/site/d.txt']);
301
+ assert.deepStrictEqual([r.done.length, r.unchanged.length, r.bytes], [2, 3, 3]);
302
+ assert.strictEqual(f.objects.get('web/site/b.txt').body.toString(), 'bb');
303
+
304
+ // Stockage → disque, deux fois
305
+ const out = path.join(dir, 'out');
306
+ fs.mkdirSync(out);
307
+ r = await c.run(api, (await c.plan(api, 'poad:web/site', out, { recursive: true })).items);
308
+ assert.deepStrictEqual([r.done.length, r.unchanged.length], [5, 0]);
309
+ fs.writeFileSync(path.join(out, 'site', 'a.txt'), 'Z'); // modifié sur le disque : recopié
310
+ r = await c.run(api, (await c.plan(api, 'poad:web/site', out, { recursive: true })).items);
311
+ assert.deepStrictEqual([r.done.length, r.unchanged.length], [1, 4]);
312
+ assert.strictEqual(fs.readFileSync(path.join(out, 'site', 'a.txt'), 'utf8'), 'A');
313
+
314
+ // Stockage → Stockage, deux fois
315
+ f.seen.length = 0;
316
+ r = await c.run(api, (await c.plan(api, 'poad:web/site', 'poad:backup/', { recursive: true })).items);
317
+ assert.deepStrictEqual([r.done.length, r.unchanged.length], [5, 0]);
318
+ f.seen.length = 0;
319
+ r = await c.run(api, (await c.plan(api, 'poad:web/site', 'poad:backup/', { recursive: true })).items);
320
+ assert.deepStrictEqual([r.done.length, r.unchanged.length, puts().length], [0, 5, 0]);
321
+
322
+ // skipIdentical: false : tout est recopié
323
+ r = await c.run(api, (await c.plan(api, 'poad:web/site', 'poad:backup/', { recursive: true })).items, { skipIdentical: false });
324
+ assert.strictEqual(r.done.length, 5);
325
+ } finally {
326
+ fs.rmSync(dir, { recursive: true, force: true });
327
+ }
328
+ });
329
+
330
+ /** Lance une commande poad storage comme le CLI, sortie et code de sortie capturés */
331
+ async function command(unit, raw, deps) {
332
+ const lines = [];
333
+ const log = console.log;
334
+ const err = console.error;
335
+ const before = process.exitCode;
336
+ process.exitCode = undefined;
337
+ console.log = (...a) => lines.push(a.join(' '));
338
+ console.error = (...a) => lines.push(a.join(' '));
339
+ try {
340
+ await unit({}, raw, deps);
341
+ return { code: process.exitCode || 0, text: lines.join('\n').replace(/\x1b\[[0-9;]*m/g, '') };
342
+ } finally {
343
+ console.log = log;
344
+ console.error = err;
345
+ process.exitCode = before;
346
+ }
347
+ }
348
+
349
+ test('poad storage cp -r: the final summary lists the failures, exit code 1; --json has failures', async () => {
350
+ const f = fakeStorage({}, { limit: 10 });
351
+ const deps = { target: async () => ({ base: 'http://x', key: 'k', fetch: f.doFetch }) };
352
+ const cp = require('../project/storage/cp');
353
+ const dir = tree();
354
+ try {
355
+ const src = path.join(dir, 'site');
356
+ const r = await command(cp, ['-r', src, 'poad:web/', '--concurrency', '3'], deps);
357
+ assert.strictEqual(r.code, 1);
358
+ const tail = r.text.split('\n').slice(-2);
359
+ assert.match(tail[0], /1 failure:/);
360
+ assert.match(tail[1], /✖ .*big\.bin: too large: the storage accepts at most 10 bytes/);
361
+ assert.match(r.text, /3 files copied, .*1 failed/);
362
+ assert.ok(!r.text.includes('Bearer') && !r.text.includes(' k '));
363
+
364
+ // Relancée : seul l'échec est retenté, rien n'est recopié
365
+ f.seen.length = 0;
366
+ const again = await command(cp, ['-r', src, 'poad:web/', '--json'], deps);
367
+ assert.strictEqual(again.code, 1);
368
+ const j = JSON.parse(again.text);
369
+ assert.deepStrictEqual(j.copied, []);
370
+ assert.strictEqual(j.unchanged.length, 3);
371
+ assert.strictEqual(j.failures.length, 1);
372
+ assert.deepStrictEqual(Object.keys(j.failures[0]).sort(), ['path', 'reason', 'to']);
373
+ assert.match(j.failures[0].reason, /at most 10 bytes/);
374
+ assert.deepStrictEqual(f.seen.filter((x) => x.put).map((x) => x.put), ['web/site/img/big.bin']);
375
+
376
+ // Sans échec : code 0
377
+ fs.rmSync(path.join(src, 'img', 'big.bin'));
378
+ const ok = await command(cp, ['-r', src, 'poad:web/'], deps);
379
+ assert.strictEqual(ok.code, 0);
380
+ assert.match(ok.text, /0 files copied, 0 B, 3 already identical at the destination/);
381
+ assert.doesNotMatch(ok.text, /failure/);
382
+
383
+ // --concurrency hors bornes : erreur d'usage, rien n'est tenté
384
+ const bad = await command(cp, ['-r', src, 'poad:web/', '--concurrency', '64'], deps);
385
+ assert.strictEqual(bad.code, 2);
386
+ assert.match(bad.text, /1 to 32/);
387
+ } finally {
388
+ fs.rmSync(dir, { recursive: true, force: true });
389
+ }
390
+ });
391
+
392
+ test('poad storage mv: a failed copy is listed at the end and left in place, exit code 1', async () => {
393
+ const f = fakeStorage({}, { limit: 3 });
394
+ f.objects.set('img/a.png', f.obj('AAA', 'image/png'));
395
+ f.objects.set('img/big.png', f.obj('BBBBBBB', 'image/png'));
396
+ const deps = { target: async () => ({ base: 'http://x', key: 'k', fetch: f.doFetch }) };
397
+ const r = await command(require('../project/storage/mv'), ['-r', 'img/', 'archive/', '--json'], deps);
398
+ assert.strictEqual(r.code, 1);
399
+ const j = JSON.parse(r.text);
400
+ assert.deepStrictEqual(j.failures.map((x) => x.path), ['img/big.png']);
401
+ assert.ok(f.objects.has('img/big.png') && !f.objects.has('img/a.png'));
402
+ });
403
+
404
+ test('client: browse, the folder view of the storage (every folder, direct files in pages) ; null on an older storage', async () => {
405
+ const f = fakeStorage({}, { folders: true });
406
+ // L'exemple de l'utilisateur : a/b/c/d/e à la racine ne donne que le dossier a
407
+ for (const k of ['a/b/c/d/e', 'a/x.txt', 'a/b/y.txt', 'racine.txt']) f.objects.set(`docs/${k}`, f.obj('xy'));
408
+ for (let i = 0; i < 2500; i++) f.objects.set(`docs/gros/f${String(i).padStart(4, '0')}.txt`, f.obj('z'));
409
+ const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
410
+ const root = await api.browse('docs', '');
411
+ assert.deepStrictEqual(s.viewEntries(root).map((e) => [e.kind, e.name, e.count]), [['folder', 'a', 3], ['folder', 'gros', 2500], ['file', 'racine.txt', undefined]]);
412
+ const a = await api.browse('docs', 'a');
413
+ assert.deepStrictEqual(s.viewEntries(a).map((e) => e.name), ['b', 'x.txt']);
414
+ assert.deepStrictEqual(s.viewEntries(await api.browse('docs', 'a/b/')).map((e) => e.name), ['c', 'y.txt']);
415
+ // 2500 fichiers directs : toutes les pages lues
416
+ const big = await api.browse('docs', 'gros');
417
+ assert.strictEqual(big.files.length, 2500);
418
+ assert.strictEqual(s.viewEntries(big).at(-1).name, 'f2499.txt');
419
+ // Un service plus ancien ignore delimiter et rend une liste : null, l'appelant reprend l'ancienne manière
420
+ const old = fakeStorage({ 'docs/a/x.txt': { body: Buffer.from('x'), type: 'text/plain' } });
421
+ assert.strictEqual(await s.client({ base: 'http://x', key: 'k', fetch: old.doFetch }).browse('docs', 'a'), null);
422
+ });
@@ -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 };