@cardinali-studio/adminkit 2.2.49 → 2.2.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/app/App.js +6 -6
  2. package/dist/app/app.css +67 -1
  3. package/dist/app/delivery.js +7 -7
  4. package/dist/app/guide/TransferGuide.js +1 -1
  5. package/dist/app/lib/deliveries.d.ts +6 -0
  6. package/dist/app/lib/delivery-capabilities.d.ts +31 -0
  7. package/dist/app/lib/delivery-capabilities.js +115 -0
  8. package/dist/app/lib/delivery-checkpoint-pipeline.d.ts +81 -0
  9. package/dist/app/lib/delivery-checkpoint-pipeline.js +195 -0
  10. package/dist/app/lib/delivery-finalize.d.ts +21 -0
  11. package/dist/app/lib/delivery-finalize.js +42 -0
  12. package/dist/app/lib/delivery-multipart-large.d.ts +18 -0
  13. package/dist/app/lib/delivery-multipart-large.js +28 -0
  14. package/dist/app/lib/delivery-network.d.ts +7 -1
  15. package/dist/app/lib/delivery-network.js +85 -18
  16. package/dist/app/lib/delivery-part-pipeline.d.ts +79 -0
  17. package/dist/app/lib/delivery-part-pipeline.js +270 -0
  18. package/dist/app/lib/delivery-upload-coordinator.d.ts +112 -0
  19. package/dist/app/lib/delivery-upload-coordinator.js +229 -0
  20. package/dist/app/lib/delivery-upload.d.ts +19 -3
  21. package/dist/app/lib/delivery-upload.js +226 -29
  22. package/dist/app/lib/upload-queue.d.ts +5 -0
  23. package/dist/app/lib/upload-queue.js +54 -29
  24. package/dist/app/routes/Deliveries.d.ts +9 -3
  25. package/dist/app/routes/Deliveries.js +299 -164
  26. package/dist/app/routes/DeliveryDashboard.js +1 -1
  27. package/dist/app/routes/DeliveryEmail.d.ts +8 -1
  28. package/dist/app/routes/DeliveryEmail.js +63 -23
  29. package/dist/app/routes/Overview.js +5 -5
  30. package/dist/app/routes/UploadDock.js +4 -3
  31. package/dist/form/media/MediaGrid.js +1 -1
  32. package/dist/functions/_shared/b2.js +98 -19
  33. package/dist/functions/_shared/delivery-activation.js +98 -0
  34. package/dist/functions/_shared/delivery-download-bundle.js +280 -0
  35. package/dist/functions/_shared/delivery-email.js +92 -13
  36. package/dist/functions/_shared/delivery-file-names.js +19 -0
  37. package/dist/functions/_shared/delivery-finalization-paid.js +31 -0
  38. package/dist/functions/_shared/delivery-finalization-storage.js +64 -0
  39. package/dist/functions/_shared/delivery-manifest-free.js +74 -0
  40. package/dist/functions/_shared/delivery-manifest.js +277 -20
  41. package/dist/functions/_shared/delivery-multipart-verification.js +68 -0
  42. package/dist/functions/_shared/delivery-request.js +74 -0
  43. package/dist/functions/_shared/delivery-storage-access.js +14 -0
  44. package/dist/functions/_shared/delivery-upload-admission.js +221 -0
  45. package/dist/functions/_shared/delivery-upload-contract.js +44 -0
  46. package/dist/functions/_shared/delivery-upload-free.js +80 -0
  47. package/dist/functions/_shared/delivery-upload-policy.js +64 -0
  48. package/dist/functions/_shared/delivery-upload-session.js +365 -0
  49. package/dist/functions/_shared/delivery-work-budget.js +49 -0
  50. package/dist/functions/api/deliveries.js +58 -17
  51. package/dist/functions/api/delivery/multipart.js +152 -15
  52. package/dist/functions/delivery-public/assets/client.js +59 -54
  53. package/dist/functions/delivery-public/assets/delivery.css +6 -2
  54. package/dist/functions/delivery-public/index.js +43 -15
  55. package/dist/functions/delivery-public/migrations/0015_delivery_activation_intents.sql +12 -0
  56. package/dist/functions/delivery-public/migrations/0016_delivery_multipart_verification.sql +16 -0
  57. package/dist/functions/delivery-public/migrations/0017_delivery_upload_admission.sql +38 -0
  58. package/dist/functions/delivery-public/migrations/0018_delivery_upload_sessions.sql +26 -0
  59. package/dist/functions/delivery-public/migrations/0019_delivery_manifest_fragments.sql +27 -0
  60. package/dist/functions/delivery-public/migrations/0020_delivery_email_reply_to.sql +1 -0
  61. package/dist/functions/index.js +3 -1
  62. package/dist/theme.css +2 -1
  63. package/package.json +1 -1
@@ -8,12 +8,19 @@ import packageInfo from "../../../../package.json" with { type: "json" };
8
8
 
9
9
  import {
10
10
  b2AbortMultipart, b2CompleteMultipart, b2CreateMultipart, b2ListParts,
11
- b2ObjectKey, b2PresignPutObject, b2PresignUploadPart, b2Head, multipartEtag,
11
+ b2ObjectKey, b2PresignPutObject, b2PresignUploadPart, b2PresignUploadParts, b2Head, multipartEtag,
12
12
  } from "../../_shared/b2.js";
13
13
 
14
14
  import { validateDeliverySourceBytes, DELIVERY_PART_BYTES, DELIVERY_MAX_ARCHIVE_BYTES } from "../../_shared/delivery-limits.js";
15
15
 
16
16
  import { manifestVersion, assertManifestWriter, assertCheckpointParts } from "../../_shared/delivery-manifest.js";
17
+ import { rejectDisabledUploadPipeline } from '../../_shared/delivery-upload-policy.js';
18
+ import { readDeliveryUploadBody, deliveryBodyErrorResponse } from '../../_shared/delivery-request.js';
19
+ import { assertUploadSessionInvocation } from '../../_shared/delivery-upload-contract.js';
20
+ import { sha256 } from '../../_shared/delivery-crypto.js';
21
+ import { verifyMultipartStep } from '../../_shared/delivery-multipart-verification.js';
22
+ import { requirePaidUpload } from '../../_shared/delivery-work-budget.js';
23
+ import { freeWork,assertFreePartRead,assertFreeCheckpointRead,needsPaid } from '../../_shared/delivery-upload-free.js';
17
24
 
18
25
  const FILENAMES = {
19
26
  originals: "originals.zip",
@@ -25,10 +32,14 @@ const confirmedDigest = value => /^[a-f0-9]{64}$/.test(value || '');
25
32
 
26
33
  export async function onRequestPost({ request, env: originalEnv }) {
27
34
  const env = requestDiagnostics(originalEnv, request.headers.get("X-Monitor-Request-Id"));
35
+ const headerRejection = rejectDisabledUploadPipeline(request);
36
+ if (headerRejection) return headerRejection;
28
37
  if (!env.DB) return json({ ok: false, error: "D1 non configurato" }, 500);
29
38
  let body;
30
- try { body = await request.json(); }
31
- catch { return json({ ok: false, error: "Corpo JSON non valido" }, 400); }
39
+ try { body = await readDeliveryUploadBody(request,env); }
40
+ catch (error) { return deliveryBodyErrorResponse(error); }
41
+ const pipelineRejection = rejectDisabledUploadPipeline(request, body);
42
+ if (pipelineRejection) return pipelineRejection;
32
43
  try {
33
44
  switch (body?.action) {
34
45
  case "create": return json({ ok: true, upload: await create(env, body) });
@@ -37,14 +48,19 @@ export async function onRequestPost({ request, env: originalEnv }) {
37
48
  case "heroPresign": return json({ ok: true, ...(await heroPresign(env, body)) });
38
49
  case "presign": return json({ ok: true, ...(await presign(env, body)) });
39
50
  case "record": return json({ ok: true, ...(await record(env, body)) });
51
+ // Unreachable through HTTP while the policy flags remain false.
52
+ case "presignBatch": return json({ ok: true, ...(await presignBatch(env, body)) });
53
+ case "recordBatch": return json({ ok: true, ...(await recordBatch(env, body)) });
40
54
  case "reconcile": return json({ ok: true, ...(await reconcile(env, body)) });
55
+ case "multipartVerifyStep": return json({ ok: true, ...(await verifyMultipartStep(env, body)) });
56
+ case "completePaid": return json({ ok: true, ...(await completeMultipartPaid(env, body)) });
41
57
  case "complete": return json({ ok: true, ...(await complete(env, body)) });
42
58
  case "abort": return json({ ok: true, ...(await abort(env, body)) });
43
59
  default: return json({ ok: false, error: "Azione multipart non valida" }, 400);
44
60
  }
45
61
  } catch (e) {
46
62
  console.error("delivery multipart:", e);
47
- return json({ ok: false, error: e instanceof Error ? e.message : String(e), retryable: e.retryable !== false, diagnostic: await technicalDiagnostic(e, { env, operation: body?.action, version: packageInfo.version, body }) }, e.status || 500);
63
+ return json({ ok: false, error: e instanceof Error ? e.message : String(e), code: e.code, retryable: e.retryable !== false, diagnostic: await technicalDiagnostic(e, { env, operation: body?.action, version: packageInfo.version, body }) }, e.status || 500);
48
64
  }
49
65
  }
50
66
 
@@ -57,6 +73,7 @@ async function heroPresign(env, body) {
57
73
  AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))
58
74
  `).bind(packageId, deliveryId).first();
59
75
  if (!pkg) throw invalid("pacchetto per la hero non trovato o scaduto");
76
+ assertUploadSessionInvocation(env, pkg);
60
77
  const heroId = crypto.randomUUID();
61
78
  const key = b2ObjectKey(pkg.storage_prefix, `heroes/${heroId}.webp`);
62
79
  const now = new Date().toISOString();
@@ -244,7 +261,92 @@ async function record(env, body) {
244
261
  return { partNumber, etag, size };
245
262
  }
246
263
 
264
+ function batchInput(body, field) {
265
+ if (new TextEncoder().encode(JSON.stringify(body)).length > 8192) {
266
+ throw Object.assign(invalid('Corpo batch troppo grande'), { status: 413, code: 'upload_budget_exceeded' });
267
+ }
268
+ if (!Array.isArray(body[field]) || !body[field].length || body[field].length > 4) {
269
+ throw Object.assign(invalid('Il batch deve contenere da una a quattro parti'), { status: 413, code: 'upload_budget_exceeded' });
270
+ }
271
+ }
272
+
273
+ async function batchUpload(env, body) {
274
+ const upload = await uploadFor(env, { ...body, action: 'partBatch' });
275
+ if (!stableOriginals(upload)) throw invalid('I batch richiedono originali Manifest v2');
276
+ return upload;
277
+ }
278
+
279
+ // Exported for local integration tests; HTTP dispatch is guarded above. These
280
+ // functions keep the same writer/storage authorization as single-part calls.
281
+ export async function presignBatch(env, body) {
282
+ batchInput(body, 'partNumbers');
283
+ const numbers = body.partNumbers;
284
+ if (new Set(numbers).size !== numbers.length || numbers.some(n => !Number.isInteger(n) || n < 1 || n > 10_000)) {
285
+ throw invalid('Numeri delle parti non validi');
286
+ }
287
+ const upload = await batchUpload(env, body);
288
+ const { results } = await env.DB.prepare(`SELECT digest FROM delivery_upload_parts
289
+ WHERE upload_id=? AND part_number IN (SELECT value FROM json_each(?))`).bind(upload.id, JSON.stringify(numbers)).all();
290
+ if ((results || []).some(p => confirmedDigest(p.digest))) throw invalid('Parte originale già confermata: non può essere sovrascritta');
291
+ const parts = await b2PresignUploadParts(env, upload.object_key, upload.b2_upload_id, numbers);
292
+ return { parts, expiresIn: 900 };
293
+ }
294
+
295
+ export async function recordBatch(env, body) {
296
+ batchInput(body, 'parts');
297
+ const parts = body.parts.map(p => {
298
+ if (!p || !Number.isInteger(p.partNumber) || p.partNumber < 1 || p.partNumber > 10_000 ||
299
+ !Number.isSafeInteger(p.size) || p.size < 1 || p.size > DELIVERY_PART_BYTES ||
300
+ typeof p.etag !== 'string' || !p.etag.trim() || p.etag.length > 256 ||
301
+ typeof p.digest !== 'string' || !confirmedDigest(p.digest)) throw invalid('Metadati del batch non validi');
302
+ return { partNumber: p.partNumber, size: p.size, etag: p.etag.trim(), digest: p.digest };
303
+ }).sort((a, b) => a.partNumber - b.partNumber);
304
+ if (new Set(parts.map(p => p.partNumber)).size !== parts.length) throw invalid('Parte duplicata nel batch');
305
+ const payload = JSON.stringify(parts);
306
+ const batchId = await sha256(JSON.stringify([body.uploadId, parts]));
307
+ if (body.batchId !== batchId) throw invalid('Identità del batch non valida');
308
+ const upload = await batchUpload(env, body);
309
+ const read = async () => (await env.DB.prepare(`SELECT part_number,etag,size,digest FROM delivery_upload_parts
310
+ WHERE upload_id=? AND part_number IN (SELECT json_extract(value,'$.partNumber') FROM json_each(?))`)
311
+ .bind(upload.id, payload).all()).results || [];
312
+ const matches = (saved, p) => saved?.etag === p.etag && saved.size === p.size && saved.digest === p.digest;
313
+ const previous = new Map((await read()).map(p => [p.part_number, p]));
314
+ if (parts.every(p => matches(previous.get(p.partNumber), p))) return { batchId, parts };
315
+ if (parts.some(p => {
316
+ const saved = previous.get(p.partNumber);
317
+ return saved && (saved.etag !== p.etag || saved.size !== p.size || (saved.digest && saved.digest !== p.digest));
318
+ })) throw invalid('Parte originale già confermata con contenuto diverso');
319
+
320
+ // One guard for the entire set, rechecked inside the D1 transaction. It
321
+ // prevents partial writes if a conflict, cancellation, expiry or takeover
322
+ // occurs after the preliminary reads. Per-part tuples are durable receipts.
323
+ const guard = `EXISTS(SELECT 1 FROM delivery_uploads u JOIN delivery_packages p ON p.id=u.package_id
324
+ JOIN deliveries d ON d.id=u.delivery_id JOIN delivery_manifest_state s ON s.package_id=p.id
325
+ WHERE u.id=? AND u.state='uploading' AND p.state='uploading' AND d.status!='deleted'
326
+ AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))
327
+ AND s.writer_token=?) AND NOT EXISTS(SELECT 1 FROM json_each(?) j
328
+ JOIN delivery_upload_parts r ON r.upload_id=? AND r.part_number=json_extract(j.value,'$.partNumber')
329
+ WHERE r.etag IS NOT json_extract(j.value,'$.etag') OR r.size IS NOT json_extract(j.value,'$.size')
330
+ OR (COALESCE(r.digest,'')!='' AND r.digest IS NOT json_extract(j.value,'$.digest')))`;
331
+ const args = [upload.id, body.writerToken, payload, upload.id];
332
+ const now = new Date().toISOString();
333
+ await env.DB.batch([
334
+ env.DB.prepare(`INSERT INTO delivery_upload_parts(upload_id,part_number,etag,digest,size,created_at)
335
+ SELECT ?,json_extract(value,'$.partNumber'),json_extract(value,'$.etag'),json_extract(value,'$.digest'),
336
+ json_extract(value,'$.size'),? FROM json_each(?) WHERE ${guard}
337
+ ON CONFLICT(upload_id,part_number) DO UPDATE SET digest=excluded.digest
338
+ WHERE COALESCE(delivery_upload_parts.digest,'')=''`)
339
+ .bind(upload.id, now, payload, ...args),
340
+ env.DB.prepare(`UPDATE delivery_uploads SET updated_at=? WHERE id=? AND ${guard}`).bind(now, upload.id, ...args),
341
+ ]);
342
+ await batchUpload(env, body);
343
+ const saved = new Map((await read()).map(p => [p.part_number, p]));
344
+ if (!parts.every(p => matches(saved.get(p.partNumber), p))) throw invalid('Batch cambiato o caricamento annullato');
345
+ return { batchId, parts };
346
+ }
347
+
247
348
  async function savedParts(env, upload) {
349
+ await assertFreePartRead(env,upload.id);
248
350
  const { results } = await env.DB.prepare(
249
351
  "SELECT part_number,etag,digest,size FROM delivery_upload_parts WHERE upload_id=? ORDER BY part_number"
250
352
  ).bind(upload.id).all();
@@ -252,15 +354,22 @@ async function savedParts(env, upload) {
252
354
  digest: p.digest || "", size: Number(p.size) }));
253
355
  }
254
356
 
255
- async function markCompleted(env, upload, bytes) {
357
+ async function markCompleted(env, upload, bytes, writerBody) {
256
358
  const now = new Date().toISOString();
257
- await env.DB.prepare(`UPDATE delivery_uploads SET state='completed',bytes=?,completed_at=?,updated_at=?
359
+ const fence = writerBody ? ` AND b2_upload_id=? AND object_key=? AND EXISTS(
360
+ SELECT 1 FROM delivery_packages p JOIN deliveries d ON d.id=p.delivery_id
361
+ JOIN delivery_manifest_state s ON s.package_id=p.id WHERE p.id=delivery_uploads.package_id
362
+ AND p.state='uploading' AND s.writer_token=? AND d.status!='deleted'
363
+ AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')))` : '';
364
+ const args = writerBody ? [upload.b2_upload_id, upload.object_key, writerBody.writerToken] : [];
365
+ const result = await env.DB.prepare(`UPDATE delivery_uploads SET state='completed',bytes=?,completed_at=?,updated_at=?
258
366
  WHERE id=? AND state='uploading'
259
- AND EXISTS (SELECT 1 FROM delivery_packages WHERE id=delivery_uploads.package_id AND state='uploading')`)
260
- .bind(bytes, now, now, upload.id).run();
367
+ AND EXISTS (SELECT 1 FROM delivery_packages WHERE id=delivery_uploads.package_id AND state='uploading')${fence}`)
368
+ .bind(bytes, now, now, upload.id, ...args).run();
369
+ if (writerBody && !result.meta.changes) throw invalid('Completamento cambiato o annullato; conserva la sessione per il recupero');
261
370
  }
262
371
 
263
- async function recoverCompleted(env, upload) {
372
+ async function recoverCompleted(env, upload, writerBody) {
264
373
  const parts = await savedParts(env, upload);
265
374
  if (!parts.length || parts.some((p, n) => p.partNumber !== n + 1)) return null;
266
375
  if (stableOriginals(upload) && parts.some(p => !confirmedDigest(p.digest))) return null;
@@ -269,18 +378,20 @@ async function recoverCompleted(env, upload) {
269
378
  const etag = await multipartEtag(parts);
270
379
  if (!head || !etag || head.bytes !== bytes || head.etag !== etag) return null;
271
380
  await assertCheckpointParts(env, upload, parts);
272
- await markCompleted(env, upload, bytes);
381
+ await markCompleted(env, upload, bytes, writerBody);
273
382
  return { parts, completed: true, bytes };
274
383
  }
275
384
 
276
- async function reconcile(env, body) {
385
+ async function reconcile(env, body, fenced = false) {
277
386
  const upload = await uploadFor(env, body, true, true);
387
+ await assertFreePartRead(env,upload.id);
388
+ await assertFreeCheckpointRead(env,upload.package_id);
278
389
  if (upload.state === "completed") return { parts: await savedParts(env, upload), completed: true, bytes: Number(upload.bytes) };
279
390
  let parts;
280
391
  try { parts = await b2ListParts(env, upload.object_key, upload.b2_upload_id); }
281
392
  catch (error) {
282
393
  if (error.status !== 404) throw error;
283
- const recovered = await recoverCompleted(env, upload);
394
+ const recovered = await recoverCompleted(env, upload, fenced ? body : undefined);
284
395
  if (recovered) return recovered;
285
396
  throw invalid("Sessione non disponibile e archivio non verificabile. Crea un nuovo caricamento.");
286
397
  }
@@ -329,10 +440,14 @@ async function reconcile(env, body) {
329
440
  ? previous.get(p.partNumber).digest : "" })), completed: false };
330
441
  }
331
442
 
332
- async function complete(env, body) {
443
+ async function complete(env, body, fenced = false) {
333
444
  if (!Number.isSafeInteger(body.bytes) || body.bytes < 1 || body.bytes > DELIVERY_MAX_ARCHIVE_BYTES) throw invalid("Dimensione archivio non valida");
445
+ if(freeWork(env)) {
446
+ if(Math.ceil(body.bytes/DELIVERY_PART_BYTES)>32||body.partCount>32)throw needsPaid();
447
+ fenced=true;
448
+ }
334
449
  const upload = await uploadFor(env, body, true, true);
335
- const reconciled = await reconcile(env, body);
450
+ const reconciled = await reconcile(env, body, fenced);
336
451
  const parts = reconciled.parts;
337
452
  const bytes = parts.reduce((n, p) => n + p.size, 0);
338
453
  if (!parts.length || parts.some((p, n) => p.partNumber !== n + 1) ||
@@ -342,10 +457,20 @@ async function complete(env, body) {
342
457
  if (stableOriginals(upload) && parts.some(p => !confirmedDigest(p.digest))) throw invalid('Parti originali non ancora confermate');
343
458
  await assertCheckpointParts(env, upload, parts);
344
459
  await b2CompleteMultipart(env, upload.object_key, upload.b2_upload_id, parts);
345
- await markCompleted(env, upload, bytes);
460
+ await markCompleted(env, upload, bytes, fenced ? body : undefined);
346
461
  return { uploadId: upload.id, key: upload.object_key, bytes };
347
462
  }
348
463
 
464
+ // The indivisible S3 completion is still the measured Paid requirement at large
465
+ // scale. Keep ALL legacy reconciliation/checkpoint/recovery checks, even after
466
+ // bounded preparation; a persisted scan is not a fresh remote authorization.
467
+ export async function completeMultipartPaid(env, body) {
468
+ requirePaidUpload(env);
469
+ const upload = await uploadFor(env, body, true, true);
470
+ if (!stableOriginals(upload)) throw invalid('Il completamento Paid richiede originali Manifest v2');
471
+ return complete(env, body, true);
472
+ }
473
+
349
474
  async function abort(env, body) {
350
475
  const upload = await uploadFor(env, body, false);
351
476
  if (!upload) return { aborted: false };
@@ -362,6 +487,7 @@ async function packageFor(env, body) {
362
487
  AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))
363
488
  `).bind(String(body.packageId || ""), String(body.id || "")).first();
364
489
  if (!pkg) throw invalid("pacchetto in caricamento non trovato");
490
+ assertUploadSessionInvocation(env, pkg);
365
491
  validateDeliverySourceBytes(pkg.source_bytes ?? 0);
366
492
  if (manifestVersion(pkg) === 2) await assertManifestWriter(env, pkg.id, body.writerToken);
367
493
  return pkg;
@@ -377,6 +503,7 @@ async function uploadFor(env, body, required = true, allowCompleted = false) {
377
503
  AND (${body.action === 'abort' ? '1' : "d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')"})
378
504
  `).bind(String(body.uploadId || "")).first();
379
505
  if (!upload && required) throw invalid("sessione multipart non trovata");
506
+ if (upload && body.action !== 'abort') assertUploadSessionInvocation(env, upload);
380
507
  // L'annullamento deve restare disponibile anche per vecchie sessioni fuori limite.
381
508
  if (upload && body.action !== "abort") validateDeliverySourceBytes(upload.declared_source_bytes ?? 0);
382
509
  if (upload && manifestVersion(upload) === 2 && body.action !== "abort") await assertManifestWriter(env, upload.package_id, body.writerToken);
@@ -390,6 +517,16 @@ function normalizeUpload(row) {
390
517
  };
391
518
  }
392
519
 
520
+ // Internal dispatcher for the metered coordinator. The public route above
521
+ // retains its existing gate/contracts; no internal permit is read from body.
522
+ export async function invokeMultipartUploadUnit(env, body) {
523
+ const handlers = { create, presign, record, reconcile, complete, presignBatch, recordBatch,
524
+ multipartVerifyStep: verifyMultipartStep, completePaid: completeMultipartPaid };
525
+ const handler = Object.hasOwn(handlers, body.action) && handlers[body.action];
526
+ if (!handler) throw invalid('Operazione multipart non disponibile');
527
+ return handler(env, body);
528
+ }
529
+
393
530
  function invalid(message) { return Object.assign(new Error(message), { status: 409, retryable: false }); }
394
531
 
395
532
  function json(data, status = 200) {
@@ -87,14 +87,15 @@
87
87
  function noticeText() {
88
88
  if (data.filesExpired) {
89
89
  return "I file di questa consegna hanno superato la data di scadenza e non sono più " +
90
- "scaricabili. Scrivi a Emanuele Cardinali se ti servono ancora.";
90
+ "scaricabili. Contatta chi ti ha inviato il link se ti servono ancora.";
91
91
  }
92
92
  if (data.preparing) {
93
- return "I file stanno arrivando. Il link è già valido: questa pagina si " +
94
- "aggiorna da sola appena sono pronte.";
93
+ return data.packages && data.packages.length
94
+ ? "Altri file sono in caricamento. Puoi già scaricare quelli disponibili."
95
+ : "I file sono in caricamento. Questa pagina si aggiornerà quando saranno pronti.";
95
96
  }
96
97
  if (data.archived) {
97
- return "Gli originali sono stati archiviati per liberare spazio. Scrivi a Emanuele Cardinali " +
98
+ return "Gli originali sono stati archiviati per liberare spazio. Contatta chi ti ha inviato il link " +
98
99
  "per richiederne il ripristino.";
99
100
  }
100
101
  return "";
@@ -124,7 +125,7 @@
124
125
  /* Il campo parte `readonly` (vedi il commento nel guscio): l'autofill non tocca un
125
126
  campo di sola lettura, così non può rimandare un codice vecchio al posto di quello
126
127
  appena digitato. Diventa scrivibile — e vuoto — appena lo si tocca. */
127
- var wake = function () { input.value = ""; input.removeAttribute("readonly"); };
128
+ var wake = function () { if (input.readOnly) { input.value = ""; input.removeAttribute("readonly"); } };
128
129
  input.addEventListener("focus", wake);
129
130
  input.addEventListener("pointerdown", wake);
130
131
 
@@ -146,61 +147,65 @@
146
147
  /* ---- download ---------------------------------------------------------------------- */
147
148
  function renderDownloads() {
148
149
  var labels = data.downloadLabels || {};
149
- var packages = (data.packages || []).filter(function (pkg) {
150
- return pkg.originals || pkg.light; // una scheda senza niente da premere non si disegna
151
- });
150
+ var packages = (data.packages || []).filter(function (p) { return p.originals || p.light; });
152
151
  if (!packages.length) return;
153
- packages.forEach(function (pkg) {
154
- var box = document.createElement("div");
155
- box.className = "dc-pack";
156
- if (packages.length > 1 && pkg.label) {
157
- var name = document.createElement("p");
158
- name.className = "dc-pack-name";
159
- name.textContent = pkg.label;
160
- box.appendChild(name);
161
- }
162
- var actions = document.createElement("div");
163
- actions.className = "dc-pack-actions";
164
- // Gli originali sono ciò per cui il cliente è qui: sono il pulsante pieno. La
165
- // versione leggera diventa primaria solo se gli originali non ci sono più.
166
- if (pkg.originals) actions.appendChild(button(pkg, "originals", labels.originals || "Scarica i file", true));
167
- if (pkg.light) actions.appendChild(button(pkg, "web", labels.web || "Versione leggera", !pkg.originals));
168
- box.appendChild(actions);
169
-
170
- var note = document.createElement("p");
171
- note.className = "dc-dl-note";
172
- note.textContent = [
173
- pkg.fileCount ? pkg.fileCount + " file" : "",
174
- pkg.bytes ? bytes(pkg.bytes) : ""
175
- ].filter(Boolean).join(" · ");
176
- if (note.textContent) box.appendChild(note);
177
-
178
- el.downloads.appendChild(box);
179
- });
180
- show(el.downloads);
181
- }
182
-
183
- function button(pkg, variant, label, primary) {
152
+ var originals = packages.filter(function (p) { return p.originals; });
153
+ var light = packages.filter(function (p) { return p.light; });
154
+ var mixed = originals.length > 0 && originals.length < packages.length;
155
+ var versions = [];
156
+ if (originals.length) versions.push({variant: mixed ? "available" : "originals", packages: packages,
157
+ label: mixed ? "Tutti i file disponibili" : "Originali", action: labels.originals || "Scarica i file"});
158
+ if (light.length) versions.push({variant: "web", packages: light, label: labels.web || "Versione leggera",
159
+ action: labels.web || "Versione leggera"});
160
+
161
+ var box = document.createElement("div"); box.className = "dc-pack";
162
+ var note = document.createElement("p"); note.className = "dc-dl-note"; note.id = "dc-download-description";
163
+ var selected = 0, selector;
164
+ if (versions.length > 1) {
165
+ var field = document.createElement("label"); field.className = "dc-version";
166
+ field.appendChild(document.createTextNode("Versione"));
167
+ selector = document.createElement("select");
168
+ versions.forEach(function (v, index) { selector.add(new Option(v.label, String(index))); });
169
+ selector.addEventListener("change", function () { selected = selector.selectedIndex; update(); });
170
+ field.appendChild(selector); box.appendChild(field);
171
+ }
184
172
  var node = document.createElement("button");
185
- node.type = "button";
186
- node.className = "dc-btn " + (primary ? "dc-btn-solid" : "dc-btn-line");
187
- node.textContent = label;
173
+ node.type = "button"; node.className = "dc-btn dc-btn-solid";
174
+ node.setAttribute("aria-describedby", note.id);
175
+ var error = document.createElement("p"); error.className = "dc-error"; error.setAttribute("role", "alert"); error.hidden = true;
176
+ box.appendChild(note); box.appendChild(node); box.appendChild(error);
177
+ el.downloads.appendChild(box); show(el.downloads); update();
178
+
179
+ function update() {
180
+ var v = versions[selected], web = v.variant === "web", group = v.packages;
181
+ var count = group.reduce(function (sum, p) { return sum + (p.fileCount || 0); }, 0);
182
+ var label = v.action;
183
+ if (v.variant !== "web" && label === "Scarica i file") label = count === 1 ? "Scarica il file" : "Scarica tutti i file";
184
+ if (web && label === "Versione leggera") label = "Scarica versione leggera";
185
+ var sizeKey = web ? "webBytes" : "originalsBytes";
186
+ var exact = group.length === 1 ? group[0][sizeKey] : null;
187
+ var summary = [web ? "Foto convertite" : (count ? count + " file" : "File"), "ZIP"];
188
+ if (Number.isSafeInteger(exact) && exact > 0) summary.push(bytes(exact));
189
+ else if (!web && !mixed) {
190
+ var sourceBytes = group.reduce(function (sum, p) { return sum + (p.bytes || 0); }, 0);
191
+ if (sourceBytes) summary[0] += " (" + bytes(sourceBytes) + ")";
192
+ }
193
+ note.textContent = summary.join(" · ");
194
+ node.textContent = label;
195
+ error.hidden = true;
196
+ }
188
197
  node.addEventListener("click", function () {
189
- var box = node.closest(".dc-pack");
190
- var previous = box.querySelector(".dc-error");
191
- if (previous) previous.remove();
192
- node.disabled = true; node.textContent = "Preparo…";
193
- post("/ticket", { packageId: pkg.id, variant: variant }).then(function (out) {
198
+ var choice = versions[selected];
199
+ error.hidden = true; node.disabled = true;
200
+ if (selector) selector.disabled = true;
201
+ node.textContent = "Preparo il download…";
202
+ post("/ticket", { packageId: "all", variant: choice.variant }).then(function (out) {
203
+ node.disabled = false; if (selector) selector.disabled = false; update();
194
204
  if (out.ok && out.body.url) { location.href = out.body.url; return; }
195
- var error = document.createElement("p");
196
- error.className = "dc-error";
197
- error.textContent = out.body.error || "Non è stato possibile avviare il download.";
198
- box.appendChild(error);
199
- }).then(function () {
200
- node.disabled = false; node.textContent = label;
205
+ error.textContent = out.body.error || "Non è stato possibile avviare il download. Riprova.";
206
+ error.hidden = false;
201
207
  });
202
208
  });
203
- return node;
204
209
  }
205
210
 
206
211
  /* ---- transfer in preparazione ------------------------------------------------------- */
@@ -279,9 +279,9 @@ body.is-message .dc-foot { display: none; }
279
279
  e il palcoscenico, che di contenuto non ne ha finché il JS non monta la prima foto,
280
280
  collasserebbe a due padding. */
281
281
  .dc { display: flex; flex-direction: column; align-items: stretch; }
282
- /* Le fotografie per prime: su un telefono sono ciò che si vuole vedere aprendo il link. */
282
+ /* Put the download and its expiry within reach before the cover on phones. */
283
283
  .dc-stage { order: 1; position: static; height: 54svh; min-height: 17rem; padding: 0.75rem 1rem; }
284
- .dc-info { order: 2; min-height: 0; padding: 1.75rem 1.25rem calc(var(--dc-mono) + 1.5rem); gap: 2rem; }
284
+ .dc-info { order: 0; min-height: 0; padding: 1.75rem 1.25rem calc(var(--dc-mono) + 1.5rem); gap: 2rem; }
285
285
  .dc-gallery { padding: 2.5rem 1.25rem 3rem; }
286
286
  .dc-shot--pair { width: 100%; }
287
287
  .dc-gate-row { flex-direction: column; align-items: stretch; }
@@ -295,3 +295,7 @@ body.is-message .dc-foot { display: none; }
295
295
  .dc-shot, .dc-set.is-out .dc-shot, .dc-lb-img { animation: none; opacity: 1; transform: none; }
296
296
  .dc-btn, .dc-cell img, .dc-lb-btn, .dc-gate-input { transition: none; }
297
297
  }
298
+
299
+ .dc-version { display: inline-flex; align-items: center; gap: .6em; font: inherit; font-size: .85rem; }
300
+ .dc-version select { font: inherit; color: inherit; color-scheme: inherit; min-height: 44px; max-width: 100%; background: transparent; border: 1px solid currentColor; border-radius: .4em; padding: .5em; }
301
+ .dc-version select:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; }
@@ -1,3 +1,4 @@
1
+ import { bundleIdentity, bundleResponse, downloadSources } from "../_shared/delivery-download-bundle.js";
1
2
  import {processDeliveryEmails} from "../_shared/delivery-email.js";
2
3
  /* Consegna pubblica: /c/<token>.
3
4
  *
@@ -13,7 +14,7 @@ import {processDeliveryEmails} from "../_shared/delivery-email.js";
13
14
  */
14
15
 
15
16
  import {
16
- b2AbortMultipart, b2Delete, b2Get, b2PresignGetObject,
17
+ b2AbortMultipart, b2Delete, b2Get, b2Head, b2PresignGetObject,
17
18
  } from "../_shared/b2.js";
18
19
  import {
19
20
  DELIVERY_LINK_MIN_LENGTH, sha256, signValue, unseal, verifyValue,
@@ -147,16 +148,23 @@ async function post({ request, env, params, waitUntil }) {
147
148
  if (access.filesExpired) {
148
149
  return json({ ok: false, error: "I file di questa consegna sono scaduti" }, 410);
149
150
  }
150
- const packageId = String(body.packageId || "");
151
- const variant = body.variant === "web" ? "web" : "originals";
152
- const pkg = access.packages.find((p) => p.id === packageId);
153
- if (!pkg || (variant === "web" && !pkg.web_key) ||
154
- (variant === "originals" && (!pkg.originals_key || access.delivery.status === "archived"))) {
151
+ const requestedId = String(body.packageId || "");
152
+ let variant = body.variant || "originals";
153
+ const all = requestedId === "all";
154
+ if (!["originals", "web"].includes(variant) && !(all && variant === "available")) {
155
+ return json({ ok: false, error: "Variante non valida" }, 400);
156
+ }
157
+ const sources = downloadSources(access, variant);
158
+ if (all ? !sources.length : !sources.some(p => p.id === requestedId)) {
155
159
  return json({ ok: false, error: "Questo download non è più disponibile" }, 404);
156
160
  }
161
+ const combined = all && sources.length > 1;
162
+ const packageId = all && !combined ? sources[0].id : requestedId;
163
+ if (!combined && variant === "available") variant = sources[0].variant;
164
+ const generation = combined ? await bundleIdentity(sources) : null;
157
165
  const ticket = await signValue(env.DELIVERY_SECRET, {
158
166
  kind: "download", linkId: access.link.id, deliveryId: access.delivery.id,
159
- packageId, variant,
167
+ packageId, variant, ...(combined ? { generation } : {}),
160
168
  }, 300);
161
169
  const now = new Date().toISOString();
162
170
  await env.DB.batch([
@@ -165,7 +173,7 @@ async function post({ request, env, params, waitUntil }) {
165
173
  env.DB.prepare(`
166
174
  INSERT INTO delivery_events(delivery_id,link_id,package_id,kind,variant,created_at)
167
175
  VALUES (?,?,?,'download_started',?,?)
168
- `).bind(access.delivery.id, access.link.id, packageId, variant, now),
176
+ `).bind(access.delivery.id, access.link.id, combined ? null : packageId, variant, now),
169
177
  ]);
170
178
  if(env.DELIVERY_EMAIL_ENABLED==='true'){
171
179
  try {
@@ -220,7 +228,8 @@ async function accessFor(env, request, token) {
220
228
  SELECT
221
229
  l.id link_id,l.delivery_id,l.pin_ciphertext,l.expires_at link_expires,l.revoked_at,
222
230
  d.client_name,d.title,d.description,d.license_notes,d.cta_enabled,d.cta_label,d.cta_url,
223
- d.expires_at delivery_expires,d.files_expires_at,d.status,d.hero_json
231
+ d.expires_at delivery_expires,d.files_expires_at,d.status,d.hero_json,
232
+ EXISTS(SELECT 1 FROM delivery_packages up WHERE up.delivery_id=d.id AND up.state='uploading') AS pending_packages
224
233
  ${env.DELIVERY_DOWNLOAD_LABELS === "true" ? ",d.download_originals_label,d.download_web_label" : ""}
225
234
  FROM delivery_links l JOIN deliveries d ON d.id=l.delivery_id
226
235
  WHERE l.token_hash=? AND l.revoked_at IS NULL AND d.status IN ('uploading','active','archived')
@@ -237,7 +246,10 @@ async function accessFor(env, request, token) {
237
246
  const expiry = earliest(row.link_expires, row.delivery_expires);
238
247
  const expired = !!expiry && new Date(expiry).getTime() < Date.now();
239
248
  const packagesResult = await env.DB.prepare(`
240
- SELECT * FROM delivery_packages WHERE delivery_id=? AND state='ready' ORDER BY position
249
+ SELECT p.*,
250
+ (SELECT bytes FROM delivery_uploads WHERE package_id=p.id AND variant='originals' AND state='completed') AS originals_bytes,
251
+ (SELECT bytes FROM delivery_uploads WHERE package_id=p.id AND variant='web' AND state='completed') AS web_bytes
252
+ FROM delivery_packages p WHERE p.delivery_id=? AND p.state='ready' ORDER BY p.position,p.id
241
253
  `).bind(row.delivery_id).all();
242
254
  let authorized = !row.pin_ciphertext;
243
255
  if (!authorized) {
@@ -267,7 +279,7 @@ async function accessFor(env, request, token) {
267
279
  filesExpiresAt: row.files_expires_at, status: row.status,
268
280
  },
269
281
  packages,
270
- filesExpired,
282
+ filesExpired, pendingPackages: !!row.pending_packages,
271
283
  protectedLink: !!row.pin_ciphertext,
272
284
  heroes: await resolveHeroes(env, filesExpired ? "[]" : row.hero_json, packages),
273
285
  };
@@ -288,7 +300,7 @@ async function publicImages(env, pkg, token, after = -1) {
288
300
  async function deliveryPage(context, access, token) {
289
301
  const d = access.delivery;
290
302
  const locked = !access.authorized;
291
- const preparing = d.status === "uploading";
303
+ const preparing = !access.filesExpired && d.status !== "archived" && (d.status === "uploading" || access.pendingPackages);
292
304
  const heroes = access.heroes.map((item) => item.kind === "media"
293
305
  ? item.url
294
306
  : item.kind === "object"
@@ -317,8 +329,9 @@ async function deliveryPage(context, access, token) {
317
329
  label: p.label,
318
330
  fileCount: Number(p.file_count || 0),
319
331
  bytes: Number(p.source_bytes || 0),
332
+ originalsBytes: p.originals_bytes ?? null, webBytes: p.web_bytes ?? null,
320
333
  originals: d.status !== "archived" && !!p.originals_key,
321
- light: !!p.web_enabled && !!p.web_key,
334
+ light: !!p.web_enabled && !!p.web_key && Number(p.web_bytes) !== 22,
322
335
  ...(p.gallery_enabled ? await publicImages(context.env, p, token) : { images: [], nextCursor: null }),
323
336
  }))),
324
337
  };
@@ -446,9 +459,23 @@ async function download(env, request, access, packageId, variant) {
446
459
  ticket.variant !== variant) {
447
460
  return new Response("Download non autorizzato", { status: 401, headers: securityHeaders("text/plain; charset=utf-8") });
448
461
  }
462
+ if (packageId === "all") {
463
+ if (access.filesExpired) return new Response(null, { status: 410 });
464
+ const sources = downloadSources(access, variant);
465
+ if (!sources.length) return new Response(null, { status: 404 });
466
+ const identity = await bundleIdentity(sources);
467
+ if (identity !== ticket.generation) {
468
+ return new Response("Il transfer è cambiato. Riapri la pagina per scaricare i file aggiornati.", { status: 409 });
469
+ }
470
+ const filename = safeFilename(access.delivery.title) + (variant === "web" ? "-web" : "") + ".zip";
471
+ return bundleResponse(request, sources, {
472
+ get: (key, range) => b2Get(env, key, range),
473
+ head: key => b2Head(env, key),
474
+ }, identity, disposition(filename));
475
+ }
449
476
  const pkg = access.packages.find((p) => p.id === packageId);
450
477
  const key = variant === "web" ? pkg?.web_key : pkg?.originals_key;
451
- if (!pkg || !key) {
478
+ if (!pkg || !key || (variant === "web" ? !pkg.web_enabled : access.delivery.status === "archived")) {
452
479
  return new Response("Non disponibile", { status: 404, headers: securityHeaders("text/plain; charset=utf-8") });
453
480
  }
454
481
  const filename = `${safeFilename(pkg.label)}${variant === "web" ? "-web" : ""}.zip`;
@@ -563,7 +590,8 @@ function securityHeaders(contentType) {
563
590
  }
564
591
 
565
592
  function isReady(access) {
566
- return access.delivery.status !== "uploading" && access.packages.length > 0;
593
+ return access.filesExpired || access.delivery.status === "archived" ||
594
+ (!access.pendingPackages && access.delivery.status !== "uploading" && access.packages.length > 0);
567
595
  }
568
596
 
569
597
  /* Un browser vero manda `Sec-Fetch-Mode: navigate` quando apre una pagina; i generatori di
@@ -0,0 +1,12 @@
1
+ -- Apply only with compatible readers/workers, before enabling common finalize.
2
+ -- Merely shipping this migration does not enable the new HTTP capabilities.
3
+ CREATE TABLE IF NOT EXISTS delivery_activation_intents (
4
+ delivery_id TEXT NOT NULL REFERENCES deliveries(id) ON DELETE CASCADE,
5
+ generation TEXT NOT NULL, link_id TEXT NOT NULL, packages_json TEXT NOT NULL CHECK(length(CAST(packages_json AS BLOB))<=16384),
6
+ policy_json TEXT NOT NULL CHECK(length(CAST(policy_json AS BLOB))<=4096),
7
+ state TEXT NOT NULL DEFAULT 'pending' CHECK(state IN ('pending','preparing','prepared','cancelled','review')),
8
+ attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL,
9
+ next_attempt_at TEXT NOT NULL, lease_token TEXT, lease_until TEXT, error_code TEXT,
10
+ PRIMARY KEY(delivery_id,generation)
11
+ );
12
+ CREATE INDEX IF NOT EXISTS delivery_activation_intents_due ON delivery_activation_intents(state,next_attempt_at);
@@ -0,0 +1,16 @@
1
+ -- Optional bounded preparation only. Apply with compatible readers before rollout.
2
+ -- This proof never substitutes the final S3 completion/checkpoint checks.
3
+ CREATE TABLE IF NOT EXISTS delivery_multipart_verification (
4
+ upload_id TEXT NOT NULL REFERENCES delivery_uploads(id) ON DELETE CASCADE,
5
+ remote_upload_id TEXT NOT NULL,
6
+ object_key TEXT NOT NULL,
7
+ expected_count INTEGER NOT NULL CHECK(expected_count BETWEEN 1 AND 10000),
8
+ expected_bytes INTEGER NOT NULL CHECK(expected_bytes BETWEEN 1 AND 167772160000),
9
+ cursor INTEGER NOT NULL DEFAULT 0,
10
+ verified_bytes INTEGER NOT NULL DEFAULT 0,
11
+ chain TEXT NOT NULL,
12
+ state TEXT NOT NULL DEFAULT 'scanning' CHECK(state IN ('scanning','verified')),
13
+ PRIMARY KEY(upload_id,remote_upload_id),
14
+ CHECK(cursor BETWEEN 0 AND expected_count),
15
+ CHECK(verified_bytes BETWEEN 0 AND expected_bytes)
16
+ );