@cardinali-studio/adminkit 2.2.49 → 2.2.51

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 (65) hide show
  1. package/dist/app/App.js +6 -6
  2. package/dist/app/app.css +110 -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 +318 -189
  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/DeliveryRecipientPreview.d.ts +14 -0
  30. package/dist/app/routes/DeliveryRecipientPreview.js +49 -0
  31. package/dist/app/routes/Overview.js +5 -5
  32. package/dist/app/routes/UploadDock.js +4 -3
  33. package/dist/form/media/MediaGrid.js +1 -1
  34. package/dist/functions/_shared/b2.js +98 -19
  35. package/dist/functions/_shared/delivery-activation.js +98 -0
  36. package/dist/functions/_shared/delivery-download-bundle.js +280 -0
  37. package/dist/functions/_shared/delivery-email.js +92 -13
  38. package/dist/functions/_shared/delivery-file-names.js +19 -0
  39. package/dist/functions/_shared/delivery-finalization-paid.js +31 -0
  40. package/dist/functions/_shared/delivery-finalization-storage.js +64 -0
  41. package/dist/functions/_shared/delivery-manifest-free.js +74 -0
  42. package/dist/functions/_shared/delivery-manifest.js +277 -20
  43. package/dist/functions/_shared/delivery-multipart-verification.js +68 -0
  44. package/dist/functions/_shared/delivery-request.js +74 -0
  45. package/dist/functions/_shared/delivery-storage-access.js +14 -0
  46. package/dist/functions/_shared/delivery-upload-admission.js +221 -0
  47. package/dist/functions/_shared/delivery-upload-contract.js +44 -0
  48. package/dist/functions/_shared/delivery-upload-free.js +80 -0
  49. package/dist/functions/_shared/delivery-upload-policy.js +64 -0
  50. package/dist/functions/_shared/delivery-upload-session.js +365 -0
  51. package/dist/functions/_shared/delivery-work-budget.js +49 -0
  52. package/dist/functions/api/deliveries.js +58 -17
  53. package/dist/functions/api/delivery/multipart.js +152 -15
  54. package/dist/functions/delivery-public/assets/client.js +59 -54
  55. package/dist/functions/delivery-public/assets/delivery.css +6 -2
  56. package/dist/functions/delivery-public/index.js +43 -15
  57. package/dist/functions/delivery-public/migrations/0015_delivery_activation_intents.sql +12 -0
  58. package/dist/functions/delivery-public/migrations/0016_delivery_multipart_verification.sql +16 -0
  59. package/dist/functions/delivery-public/migrations/0017_delivery_upload_admission.sql +38 -0
  60. package/dist/functions/delivery-public/migrations/0018_delivery_upload_sessions.sql +26 -0
  61. package/dist/functions/delivery-public/migrations/0019_delivery_manifest_fragments.sql +27 -0
  62. package/dist/functions/delivery-public/migrations/0020_delivery_email_reply_to.sql +1 -0
  63. package/dist/functions/index.js +3 -1
  64. package/dist/theme.css +2 -1
  65. package/package.json +1 -1
@@ -6,8 +6,27 @@ import { DIAGNOSTICS } from "./diagnostics.js";
6
6
  * PUT a breve durata che il browser usa direttamente verso il bucket privato.
7
7
  */
8
8
 
9
+ import { storageControlRequest } from "./delivery-storage-access.js";
10
+
9
11
  const enc = new TextEncoder();
10
12
  import {deliveryStorageScope} from './delivery-storage-scope.js';
13
+ import { DELIVERY_WORK_BUDGET } from './delivery-work-budget.js';
14
+ import { freeWork, FREE_UPLOAD_UNIT, needsPaid } from './delivery-upload-free.js';
15
+
16
+ async function controlText(env,response) {
17
+ if(!freeWork(env))return response.text();
18
+ const budget=freeWork(env),limit=Math.min(FREE_UPLOAD_UNIT.dataBytes,FREE_UPLOAD_UNIT.metadataBytes-budget.used.metadataBytes);
19
+ const reader=response.body?.getReader(),chunks=[];let size=0;
20
+ try{
21
+ if(Number(response.headers.get('content-length'))>limit)throw needsPaid();
22
+ if(reader)for(;;){const {value,done}=await reader.read();if(done)break;size+=value.byteLength;
23
+ if(size>limit)throw needsPaid();chunks.push(value);}
24
+ }finally{await reader?.cancel();}
25
+ budget.readBytes(size);
26
+ const data=new Uint8Array(size);let offset=0;
27
+ for(const chunk of chunks){data.set(chunk,offset);offset+=chunk.byteLength;}
28
+ return new TextDecoder('utf-8',{fatal:true}).decode(data);
29
+ }
11
30
 
12
31
  export function b2Configured(env) {
13
32
  return !!(env.B2_ENDPOINT && env.B2_REGION && env.B2_BUCKET &&
@@ -54,10 +73,11 @@ export async function b2Request(env, method, key, options = {}) {
54
73
  `SignedHeaders=${signedNames.join(";")}, Signature=${signature}`);
55
74
 
56
75
  const listing = options.query && ("versions" in options.query || "uploads" in options.query);
76
+ env[DELIVERY_WORK_BUDGET]?.external();
57
77
  const started = performance.now();
58
78
  const step = { component: 'b2', operation: method.toUpperCase(), stage: options.query?.uploadId ? 'multipart' : listing ? 'listing' : /manifest/.test(key) ? 'manifest' : 'object' };
59
79
  try {
60
- const response = await fetch(url, { method, headers, body, signal: method === "GET" && !options.query?.uploadId && !listing ? undefined : AbortSignal.timeout(60_000) });
80
+ const response = await fetch(url, { method, headers, body, ...(env[DELIVERY_WORK_BUDGET] ? { redirect: 'error' } : {}), signal: options.signal ?? (method === "GET" && !options.query?.uploadId && !listing ? undefined : AbortSignal.timeout(60_000)) });
61
81
  env[DIAGNOSTICS]?.record({ ...step, status: response.status, ok: response.ok, durationMs: Math.round(performance.now() - started), providerRequestId: response.headers.get('x-amz-request-id') });
62
82
  return response;
63
83
  } catch (error) {
@@ -70,6 +90,21 @@ export async function b2PresignUploadPart(env, key, uploadId, partNumber, expire
70
90
  return presignObject(env, "PUT", key, { partNumber: String(partNumber), uploadId }, expires, 3600);
71
91
  }
72
92
 
93
+ // Request-local derivation only: never retain credentials/signing keys across
94
+ // requests, dates, regions or installations.
95
+ export async function b2PresignUploadParts(env, key, uploadId, partNumbers) {
96
+ if (!Array.isArray(partNumbers) || !partNumbers.length || partNumbers.length > 4 ||
97
+ new Set(partNumbers).size !== partNumbers.length ||
98
+ partNumbers.some(n => !Number.isInteger(n) || n < 1 || n > 10_000)) throw new Error('Gruppo di parti non valido');
99
+ deliveryStorageScope(env, 'PUT', key, { uploadId });
100
+ assertConfig(env);
101
+ const amzDate = stamp(new Date());
102
+ const signer = { amzDate, key: await signingKey(env.B2_APPLICATION_KEY, amzDate.slice(0, 8), env.B2_REGION) };
103
+ return Promise.all(partNumbers.map(async partNumber => ({ partNumber,
104
+ url: await presignObject(env, 'PUT', key, { partNumber: String(partNumber), uploadId }, 900, 3600, signer),
105
+ })));
106
+ }
107
+
73
108
  export async function b2PresignPutObject(env, key, expires = 900) {
74
109
  return presignObject(env, "PUT", key, {}, expires, 3600);
75
110
  }
@@ -83,13 +118,12 @@ export async function b2PresignGetObject(env, key, options = {}) {
83
118
  return presignObject(env, "GET", key, query, options.expires ?? 86_400, 604_800);
84
119
  }
85
120
 
86
- async function presignObject(env, method, key, query, expires, maxExpires) {
121
+ async function presignObject(env, method, key, query, expires, maxExpires, signer) {
87
122
  query = deliveryStorageScope(env, method, key, query);
88
123
  assertConfig(env);
89
124
  const url = objectUrl(env, key);
90
125
  addQuery(url, query);
91
- const now = new Date();
92
- const amzDate = stamp(now);
126
+ const amzDate = signer?.amzDate || stamp(new Date());
93
127
  const date = amzDate.slice(0, 8);
94
128
  const scope = `${date}/${env.B2_REGION}/s3/aws4_request`;
95
129
  url.searchParams.set("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
@@ -108,17 +142,19 @@ async function presignObject(env, method, key, query, expires, maxExpires) {
108
142
  const stringToSign = [
109
143
  "AWS4-HMAC-SHA256", amzDate, scope, await sha256Bytes(enc.encode(canonical)),
110
144
  ].join("\n");
111
- const signature = hex(await hmac(await signingKey(env.B2_APPLICATION_KEY, date, env.B2_REGION), stringToSign));
145
+ const signature = hex(await hmac(signer?.key || await signingKey(env.B2_APPLICATION_KEY, date, env.B2_REGION), stringToSign));
112
146
  url.searchParams.set("X-Amz-Signature", signature);
113
147
  return url.toString();
114
148
  }
115
149
 
150
+ export const b2ControlRequest = storageControlRequest(b2Request);
151
+
116
152
  export async function b2CreateMultipart(env, key, contentType = "application/zip") {
117
- const res = await b2Request(env, "POST", key, {
153
+ const res = await b2ControlRequest(env, "POST", key, {
118
154
  query: { uploads: "" },
119
155
  headers: { "Content-Type": contentType },
120
156
  });
121
- const text = await res.text();
157
+ const text = await controlText(env,res);
122
158
  if (!res.ok) throw new Error(`B2 create multipart ${res.status}: ${text.slice(0, 300)}`);
123
159
  const uploadId = xml(text, "UploadId");
124
160
  if (!uploadId) throw new Error("B2 non ha restituito uploadId");
@@ -129,30 +165,35 @@ export async function b2CompleteMultipart(env, key, uploadId, parts) {
129
165
  const body = `<CompleteMultipartUpload>${parts.map((p) =>
130
166
  `<Part><PartNumber>${p.partNumber}</PartNumber><ETag>${escapeXml(p.etag)}</ETag></Part>`
131
167
  ).join("")}</CompleteMultipartUpload>`;
132
- const res = await b2Request(env, "POST", key, {
168
+ const res = await b2ControlRequest(env, "POST", key, {
133
169
  query: { uploadId },
134
170
  headers: { "Content-Type": "application/xml" },
135
171
  body,
136
172
  });
137
- const text = await res.text();
173
+ const text = await controlText(env,res);
138
174
  if (!res.ok || /<Error[>\s]/.test(text)) throw new Error(`B2 complete multipart ${res.status}: ${text.slice(0, 300)}`);
139
175
  return { etag: xml(text, "ETag"), versionId: xml(text, "VersionId") };
140
176
  }
141
177
 
142
178
  export async function b2AbortMultipart(env, key, uploadId) {
143
- const res = await b2Request(env, "DELETE", key, { query: { uploadId } });
179
+ const res = await b2ControlRequest(env, "DELETE", key, { query: { uploadId } });
144
180
  if (!res.ok && res.status !== 404) {
145
181
  throw new Error(`B2 abort multipart ${res.status}: ${(await res.text()).slice(0, 300)}`);
146
182
  }
147
183
  }
148
184
 
149
185
  export async function b2ListParts(env, key, uploadId) {
186
+ if(freeWork(env)) {
187
+ const page=await b2ListPartsPage(env,key,uploadId,0,{contiguous:false});
188
+ if(page.truncated)throw needsPaid();
189
+ return page.parts;
190
+ }
150
191
  const parts = [];
151
192
  let marker = "";
152
193
  for (let page = 0; page < 10; page++) {
153
194
  const query = { uploadId, "max-parts": "1000" };
154
195
  if (marker) query["part-number-marker"] = marker;
155
- const res = await b2Request(env, "GET", key, { query });
196
+ const res = await b2ControlRequest(env, "GET", key, { query });
156
197
  const text = await res.text();
157
198
  if (!res.ok) throw Object.assign(new Error(`B2 list parts ${res.status}: ${text.slice(0, 300)}`), { status: res.status });
158
199
  for (const block of text.matchAll(/<Part>([\s\S]*?)<\/Part>/g)) {
@@ -169,6 +210,41 @@ export async function b2ListParts(env, key, uploadId) {
169
210
  return parts.filter((p) => Number.isInteger(p.partNumber) && p.partNumber > 0 && p.etag);
170
211
  }
171
212
 
213
+ // New bounded verifier only; the legacy reconciliation contract is unchanged.
214
+ export async function b2ListPartsPage(env, key, uploadId, marker = 0, {contiguous=true}={}) {
215
+ if (!Number.isSafeInteger(marker) || marker < 0 || marker >= 10_000) throw new Error('Marker multipart non valido');
216
+ const res = await b2ControlRequest(env, 'GET', key, { query: { uploadId, 'max-parts': '32', 'part-number-marker': String(marker) } });
217
+ let text;
218
+ if(freeWork(env))text=await controlText(env,res);
219
+ else {
220
+ const reader = res.body?.getReader(), chunks = []; let size = 0;
221
+ try {
222
+ if (Number(res.headers.get('content-length')) > 32768) throw new Error('Risposta ListParts troppo grande');
223
+ if (reader) for (;;) {
224
+ const { value, done } = await reader.read(); if (done) break;
225
+ size += value.length;
226
+ if (size > 32768) throw new Error('Risposta ListParts troppo grande');
227
+ chunks.push(value);
228
+ }
229
+ } finally { await reader?.cancel(); }
230
+ if (!res.ok) throw Object.assign(new Error(`B2 list parts ${res.status}`), { status: res.status });
231
+ const data = new Uint8Array(size); let offset = 0;
232
+ for (const chunk of chunks) { data.set(chunk, offset); offset += chunk.length; }
233
+ text = new TextDecoder('utf-8', { fatal: true }).decode(data);
234
+ }
235
+ if(!res.ok)throw Object.assign(new Error(`B2 list parts ${res.status}`),{status:res.status});
236
+ const truncated = xml(text, 'IsTruncated').toLowerCase();
237
+ if (!['true','false'].includes(truncated) || !/<ListPartsResult[>\s]/.test(text)) throw new Error('Risposta ListParts non valida');
238
+ const parts = [...text.matchAll(/<Part>([\s\S]*?)<\/Part>/g)].map(([, part]) => ({
239
+ partNumber: Number(xml(part, 'PartNumber')), etag: xml(part, 'ETag'), size: Number(xml(part, 'Size')),
240
+ }));
241
+ if (parts.length > 32 || parts.some((p, i) => !Number.isSafeInteger(p.partNumber)||p.partNumber<1||p.partNumber>10000||
242
+ (contiguous?p.partNumber!==marker+i+1:p.partNumber<=(i?parts[i-1].partNumber:marker)) || !p.etag || p.etag.length > 256 || !Number.isSafeInteger(p.size) || p.size < 1)) throw new Error('Pagina multipart non valida');
243
+ const next = Number(xml(text, 'NextPartNumberMarker'));
244
+ if (truncated === 'true' && (!parts.length || next !== parts.at(-1).partNumber || next >= 10_000)) throw new Error('Cursore multipart non valido');
245
+ return { parts, truncated: truncated === 'true' };
246
+ }
247
+
172
248
  export async function b2PutSmall(env, key, body, contentType) {
173
249
  let lastFailure = "";
174
250
  for (let attempt = 0; attempt < 5; attempt++) {
@@ -177,18 +253,19 @@ export async function b2PutSmall(env, key, body, contentType) {
177
253
  /* Ogni tentativo passa di nuovo da b2Request: data e firma SigV4 vengono
178
254
  rigenerate. Il PUT è idempotente perché il manifest usa sempre la
179
255
  stessa chiave immutabile del pacchetto. */
180
- res = await b2Request(env, "PUT", key, {
256
+ res = await b2ControlRequest(env, "PUT", key, {
181
257
  headers: { "Content-Type": contentType },
182
258
  body,
183
259
  });
184
260
  } catch (error) {
261
+ if (error.code === 'upload_budget_exceeded'||error.retryable===false) throw error;
185
262
  lastFailure = error instanceof Error ? error.message : String(error);
186
263
  if (attempt === 4) throw new Error(`B2 put: ${lastFailure}`);
187
264
  await retryDelay(null, attempt);
188
265
  continue;
189
266
  }
190
- if (res.ok) return;
191
- const detail = (await res.text()).replace(/\s+/g, " ").trim().slice(0, 300);
267
+ if (res.ok) { await res.body?.cancel(); return; }
268
+ const detail = (await controlText(env,res)).replace(/\s+/g, " ").trim().slice(0, 300);
192
269
  lastFailure = `${res.status}${detail ? `: ${detail}` : ""}`;
193
270
  if (!transientStatus(res.status) || attempt === 4) {
194
271
  throw new Error(`B2 put ${lastFailure}`);
@@ -204,20 +281,22 @@ export function b2Get(env, key, range) {
204
281
  }
205
282
 
206
283
  export async function b2Head(env, key) {
207
- const res = await b2Request(env, "HEAD", key);
208
- if (res.status === 404) return null;
284
+ const res = await b2ControlRequest(env, "HEAD", key);
285
+ if (res.status === 404) { await res.body?.cancel(); return null; }
209
286
  if ([403, 500, 502, 503, 504].includes(res.status)) {
210
287
  // Some edge paths reject HEAD while the same SigV4 GET succeeds. Request
211
288
  // exactly one byte and validate Content-Range; never buffer a whole ZIP.
212
289
  await res.body?.cancel();
213
290
  return b2RangeMetadata(env, key);
214
291
  }
215
- if (!res.ok) throw new Error(`B2 head ${res.status}`);
216
- return { bytes: Number(res.headers.get("content-length")), etag: (res.headers.get("etag") || "").replaceAll('"', "") };
292
+ if (!res.ok) { await res.body?.cancel(); throw new Error(`B2 head ${res.status}`); }
293
+ const metadata = { bytes: Number(res.headers.get("content-length")), etag: (res.headers.get("etag") || "").replaceAll('"', "") };
294
+ await res.body?.cancel();
295
+ return metadata;
217
296
  }
218
297
 
219
298
  export async function b2RangeMetadata(env, key) {
220
- const partial = await b2Request(env, "GET", key, {headers: {Range: "bytes=0-0"}});
299
+ const partial = await b2ControlRequest(env, "GET", key, {headers: {Range: "bytes=0-0"}});
221
300
  const range = /^bytes 0-0\/(\d+)$/.exec(partial.headers.get("content-range") || "");
222
301
  await partial.body?.cancel();
223
302
  if (partial.status === 404) return null;
@@ -0,0 +1,98 @@
1
+ import { randomToken, seal, sha256, DELIVERY_LINK_TOKEN_BYTES } from './delivery-crypto.js';
2
+ import { assertManifestWriter } from './delivery-manifest.js';
3
+ import { captureReadyNotificationPolicy, processDeliveryEmails } from './delivery-email.js';
4
+ import { measureFinalization } from './delivery-finalization-storage.js';
5
+ import { assertUploadSessionInvocation } from './delivery-upload-contract.js';
6
+ import { freeWork,needsPaid } from './delivery-upload-free.js';
7
+ const fail = (message, status=409) => Object.assign(new Error(message), {status,code:'delivery_manifest',retryable:status>=500});
8
+
9
+ // Normalize real execution contexts without manufacturing a fake scheduler.
10
+ export function deliveryWaitUntil(context) {
11
+ if (typeof context?.waitUntil === 'function') return context.waitUntil.bind(context);
12
+ const execution = context?.executionCtx || context?.ctx;
13
+ return typeof execution?.waitUntil === 'function' ? execution.waitUntil.bind(execution) : null;
14
+ }
15
+
16
+ export async function activateDeliveryMinimal(env, body, context={}, trace) {
17
+ const id=String(body.id||''), packageId=String(body.packageId||'');
18
+ if(!id||!packageId)throw fail('Transfer o pacchetto mancante');
19
+ if(!await env.DB.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='delivery_activation_intents'").first()) throw fail('Migrazione della finalizzazione necessaria',503);
20
+ await assertManifestWriter(env,packageId,body.writerToken);
21
+ const current=await env.DB.prepare(`SELECT id,status FROM deliveries WHERE id=? AND status!='deleted'
22
+ AND (files_expires_at IS NULL OR files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))
23
+ AND (expires_at IS NULL OR expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))`).bind(id).first();
24
+ if(!current)throw fail('Transfer non disponibile');
25
+ if(freeWork(env)) {
26
+ const bound=await env.DB.prepare(`SELECT COUNT(*) n,COALESCE(SUM(length(CAST(manifest_json AS BLOB))+1024),0) bytes
27
+ FROM (SELECT manifest_json FROM delivery_packages WHERE delivery_id=? AND state!='deleted' LIMIT 33)`).bind(id).first();
28
+ if(bound.n>32||bound.bytes>12288||!freeWork(env).canRead(bound.bytes))throw needsPaid();
29
+ }
30
+ const packages=(await env.DB.prepare(`SELECT id,state,originals_key,web_enabled,web_key,gallery_enabled,thumbs_key,
31
+ json_extract(manifest_json,'$.version') manifest_version,manifest_key,manifest_json FROM delivery_packages
32
+ WHERE delivery_id=? AND state!='deleted' ORDER BY id LIMIT 33`).bind(id).all()).results||[];
33
+ if(!packages.length||packages.length>32||packages.some(p=>!['uploading','ready'].includes(p.state)||p.state==='ready'&&(!p.originals_key||(p.web_enabled||p.gallery_enabled)&&!p.web_key||p.gallery_enabled&&!p.thumbs_key))) throw fail('Pacchetti non validi o budget di attivazione superato');
34
+ const target=packages.find(p=>p.id===packageId);
35
+ if(target)assertUploadSessionInvocation(env,target);
36
+ if(target?.manifest_version!==2)throw fail('Il percorso minimo richiede il pacchetto Manifest v2');
37
+ if(!target.originals_key||(target.web_enabled||target.gallery_enabled)&&!target.web_key||target.gallery_enabled&&!target.thumbs_key)throw fail('Archivi del pacchetto non disponibili');
38
+ const proof=await env.DB.prepare(`SELECT o.object_key,o.digest,o.verified,s.state FROM delivery_manifest_objects o
39
+ JOIN delivery_manifest_state s ON s.package_id=o.package_id WHERE o.package_id=? AND o.page_number=-1`).bind(packageId).first();
40
+ const marker=await env.DB.prepare("SELECT json_extract(manifest_json,'$.root') root,json_extract(manifest_json,'$.digest') digest FROM delivery_packages WHERE id=?").bind(packageId).first();
41
+ if(!proof?.verified||proof.state!=='ready'||proof.object_key!==target.manifest_key||proof.object_key!==marker.root||proof.digest!==marker.digest)throw fail('Manifest finale non verificato');
42
+ const ids=packages.map(p=>p.id), packagesJson=JSON.stringify(ids),generation=await sha256(ids.join('\n'));
43
+ const policy=await measureFinalization(trace,'notificationPolicy',()=>captureReadyNotificationPolicy(env,id));
44
+ const now=new Date().toISOString();
45
+ const existing=await env.DB.prepare(`SELECT id FROM delivery_links WHERE delivery_id=? AND revoked_at IS NULL
46
+ AND (expires_at IS NULL OR expires_at>?) ORDER BY created_at,id LIMIT 1`).bind(id,now).first();
47
+ let link;
48
+ if(!existing){
49
+ const token=randomToken(DELIVERY_LINK_TOKEN_BYTES);
50
+ link={id:crypto.randomUUID(),hash:await sha256(token),cipher:await seal(env.DELIVERY_SECRET,token)};
51
+ }
52
+ const baseGuard=`EXISTS(SELECT 1 FROM deliveries d WHERE d.id=? AND d.status!='deleted'
53
+ AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))
54
+ AND (d.expires_at IS NULL OR d.expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')))
55
+ AND (SELECT json_group_array(id) FROM (SELECT id FROM delivery_packages WHERE delivery_id=? AND state!='deleted' ORDER BY id))=?
56
+ AND NOT EXISTS(SELECT 1 FROM delivery_packages WHERE delivery_id=? AND state='ready' AND
57
+ (originals_key IS NULL OR ((web_enabled=1 OR gallery_enabled=1) AND web_key IS NULL) OR (gallery_enabled=1 AND thumbs_key IS NULL)))
58
+ AND EXISTS(SELECT 1 FROM delivery_manifest_state s JOIN delivery_packages p ON p.id=s.package_id
59
+ JOIN delivery_manifest_objects o ON o.package_id=p.id AND o.page_number=-1 WHERE p.id=? AND s.writer_token=? AND s.state='ready'
60
+ AND p.state IN ('uploading','ready') AND p.originals_key IS NOT NULL AND o.verified=1 AND o.object_key=p.manifest_key
61
+ AND ((p.web_enabled=0 AND p.gallery_enabled=0) OR p.web_key IS NOT NULL) AND (p.gallery_enabled=0 OR p.thumbs_key IS NOT NULL)
62
+ AND o.digest=json_extract(p.manifest_json,'$.digest'))
63
+ AND (${policy.guard})`;
64
+ const baseArgs=[id,id,packagesJson,id,packageId,body.writerToken,...policy.args];
65
+ const guard=`${baseGuard} AND EXISTS(SELECT 1 FROM delivery_links WHERE delivery_id=? AND revoked_at IS NULL
66
+ AND (expires_at IS NULL OR expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')))`;
67
+ const args=[...baseArgs,id];
68
+ const publishGuard=`${guard} AND EXISTS(SELECT 1 FROM delivery_activation_intents WHERE delivery_id=? AND generation=?)`;
69
+ const publishArgs=[...args,id,generation];
70
+ const statements=[];
71
+ if(link)statements.push(env.DB.prepare(`INSERT INTO delivery_links(id,delivery_id,label,token_hash,token_ciphertext,created_at)
72
+ SELECT ?,?,'Link principale',?,?,? WHERE ${baseGuard} AND NOT EXISTS(SELECT 1 FROM delivery_links WHERE delivery_id=? AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')))`)
73
+ .bind(link.id,id,link.hash,link.cipher,now,...baseArgs,id));
74
+ statements.push(
75
+ env.DB.prepare(`INSERT OR IGNORE INTO delivery_activation_intents(delivery_id,generation,link_id,packages_json,policy_json,created_at,next_attempt_at)
76
+ SELECT ?,?,l.id,?,?,?,? FROM delivery_links l WHERE l.delivery_id=? AND l.revoked_at IS NULL
77
+ AND (l.expires_at IS NULL OR l.expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))
78
+ AND ${guard} ORDER BY l.created_at,l.id LIMIT 1`).bind(id,generation,packagesJson,JSON.stringify(policy.targets),now,now,id,...args),
79
+ env.DB.prepare(`UPDATE delivery_packages SET state='ready' WHERE id=? AND delivery_id=? AND state='uploading' AND ${publishGuard}`).bind(packageId,id,...publishArgs),
80
+ env.DB.prepare(`UPDATE deliveries SET status='active',activated_at=COALESCE(activated_at,?),updated_at=?,version=version+1
81
+ WHERE id=? AND status!='active' AND ${publishGuard}`).bind(now,now,id,...publishArgs),
82
+ env.DB.prepare(`UPDATE delivery_packages SET originals_purge_after=NULL WHERE delivery_id=? AND state='ready' AND ${publishGuard}`).bind(id,...publishArgs),
83
+ );
84
+ await measureFinalization(trace,'activationCommit',()=>env.DB.batch(statements));
85
+ await assertManifestWriter(env,packageId,body.writerToken);
86
+ const result=await env.DB.prepare(`SELECT d.status,i.state FROM deliveries d JOIN delivery_activation_intents i ON i.delivery_id=d.id
87
+ JOIN delivery_packages p ON p.delivery_id=d.id WHERE d.id=? AND i.generation=? AND d.status='active' AND p.id=? AND p.state='ready'
88
+ AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))
89
+ AND (d.expires_at IS NULL OR d.expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))`).bind(id,generation,packageId).first();
90
+ if(!result)throw fail('Attivazione cambiata o non persistita');
91
+ const waitUntil=deliveryWaitUntil(context);
92
+ if(waitUntil){
93
+ const task=processDeliveryEmails(env,{prepareReadyIntents:true}).catch(()=>console.error('Transfer notification retry pending'));
94
+ // A broken scheduler must not undo the already durable activation/intent.
95
+ try{waitUntil(task);}catch{void task.catch(()=>{});}
96
+ }
97
+ return {activated:true,id,status:'active',generation,notificationIntent:result.state};
98
+ }
@@ -0,0 +1,280 @@
1
+ // Reuse the STORE payloads and CRCs in the immutable package ZIPs. Only ZIP
2
+ // metadata is rewritten. A contiguous group of files needs one storage GET,
3
+ // including when a browser resumes in the middle of a file.
4
+ const U32 = 0xffffffff;
5
+ const encoder = new TextEncoder();
6
+ const decoder = new TextDecoder('utf-8', { fatal: true });
7
+ const view = bytes => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
8
+ function valid(condition) { if (!condition) throw Error('Archivio sorgente incompleto'); }
9
+ function uint64(v, at) {
10
+ const n = Number(v.getBigUint64(at, true));
11
+ valid(Number.isSafeInteger(n)); return n;
12
+ }
13
+
14
+ export function downloadSources(access, variant) {
15
+ if (!['originals', 'web', 'available'].includes(variant)) return [];
16
+ return access.packages.flatMap(p => {
17
+ const original = access.delivery.status !== 'archived' && p.originals_key;
18
+ const useWeb = variant === 'web' || (variant === 'available' && !original);
19
+ const key = useWeb ? p.web_enabled && Number(p.web_bytes) !== 22 && p.web_key : original;
20
+ return key ? [{ id: p.id, key, variant: useWeb ? 'web' : 'originals', bytes: Number(useWeb ? p.web_bytes : p.originals_bytes) }] : [];
21
+ });
22
+ }
23
+
24
+ export async function bundleIdentity(sources) {
25
+ const bytes = await crypto.subtle.digest('SHA-256', encoder.encode(JSON.stringify(
26
+ ['zip-v1', ...sources.map(s => [s.id, s.key])])));
27
+ return Array.from(new Uint8Array(bytes), b => b.toString(16).padStart(2, '0')).join('');
28
+ }
29
+
30
+ async function storageRange(io, source, start, end) {
31
+ if (source.cached) return new Blob([source.cached.subarray(start, end + 1)]).stream();
32
+ const res = await io.get(source.key, `bytes=${start}-${end}`);
33
+ if (res.status !== 206 || res.headers.get('content-range') !== `bytes ${start}-${end}/${source.bytes}` || !res.body) {
34
+ await res.body?.cancel(); throw Error('Intervallo sorgente non disponibile');
35
+ }
36
+ return res.body;
37
+ }
38
+
39
+ async function metadata(io, source, start, end) {
40
+ const stream = await storageRange(io, source, start, end);
41
+ const bytes = new Uint8Array(await new Response(stream).arrayBuffer());
42
+ valid(bytes.length === end - start + 1);
43
+ return bytes;
44
+ }
45
+
46
+ // Each package was produced by ZipStream, with an uncommented end record.
47
+ // Walk the original central directory in bounded windows, including ZIP64.
48
+ async function* directory(io, source, cacheBudget) {
49
+ if (!source.bytes) source.bytes = (await io.head(source.key))?.bytes;
50
+ valid(Number.isSafeInteger(source.bytes) && source.bytes >= 22);
51
+ const tailStart = Math.max(0, source.bytes - 65536);
52
+ const tail = await metadata(io, source, tailStart, source.bytes - 1);
53
+ if (!tailStart && tail.length <= cacheBudget.remaining) {
54
+ source.cached = tail; cacheBudget.remaining -= tail.length;
55
+ }
56
+ const v = view(tail), end = tail.length - 22;
57
+ valid(v.getUint32(end, true) === 0x06054b50 && v.getUint16(end + 20, true) === 0);
58
+ let count = v.getUint16(end + 10, true), size = v.getUint32(end + 12, true), start = v.getUint32(end + 16, true);
59
+ if (count === 65535 || size === U32 || start === U32) {
60
+ const z = end - 76;
61
+ valid(z >= 0 && v.getUint32(z, true) === 0x06064b50 && v.getUint32(end - 20, true) === 0x07064b50);
62
+ count = uint64(v, z + 32); size = uint64(v, z + 40); start = uint64(v, z + 48);
63
+ }
64
+ valid(start + size <= source.bytes - 22 && count <= Math.floor(size / 46));
65
+ let window = tail, from = tailStart;
66
+ const finish = start + size;
67
+ async function ensure(at, length) {
68
+ valid(at + length <= finish);
69
+ if (at < from || at + length > from + window.length) {
70
+ from = at;
71
+ window = await metadata(io, source, at, Math.min(finish, at + Math.max(512 * 1024, length)) - 1);
72
+ }
73
+ }
74
+ let at = start, previous;
75
+ for (let i = 0; i < count; i++) {
76
+ await ensure(at, 46);
77
+ let d = view(window.subarray(at - from));
78
+ const names = d.getUint16(28, true), extras = d.getUint16(30, true);
79
+ const length = 46 + names + extras + d.getUint16(32, true);
80
+ await ensure(at, length);
81
+ const bytes = window.subarray(at - from, at - from + length);
82
+ d = view(bytes);
83
+ const flags = d.getUint16(8, true);
84
+ valid(d.getUint32(0, true) === 0x02014b50 && d.getUint16(10, true) === 0 && !(flags & 1));
85
+ let size = d.getUint32(24, true), packed = d.getUint32(20, true), offset = d.getUint32(42, true);
86
+ for (let pos = 46 + names; pos < 46 + names + extras;) {
87
+ const type = d.getUint16(pos, true), length = d.getUint16(pos + 2, true);
88
+ let n = pos + 4; pos = n + length; valid(pos <= 46 + names + extras);
89
+ if (type !== 1) continue;
90
+ if (size === U32) { size = uint64(d, n); n += 8; }
91
+ if (packed === U32) { packed = uint64(d, n); n += 8; }
92
+ if (offset === U32) { offset = uint64(d, n); n += 8; }
93
+ valid(n <= pos);
94
+ }
95
+ valid(size === packed && offset < start);
96
+ const entry = { path: decoder.decode(bytes.subarray(46, 46 + names)), size, local: offset,
97
+ descriptor: flags & 8 ? (size >= U32 ? 24 : 16) : 0,
98
+ stamp: d.getUint32(12, true), crc: d.getUint32(16, true) };
99
+ if (previous) yield locate(previous, offset);
100
+ previous = entry; at += length;
101
+ }
102
+ valid(at === finish);
103
+ if (previous) yield locate(previous, start);
104
+ }
105
+ function locate(entry, next) {
106
+ entry.input = next - entry.descriptor - entry.size;
107
+ valid(entry.input >= entry.local + 30);
108
+ return entry;
109
+ }
110
+
111
+ // Keep folder structure and both copies of same-named files, even on
112
+ // case-insensitive filesystems. Remember a renamed folder for its siblings.
113
+ function uniquePath(path, used, folders, counters) {
114
+ const parts = path.replace(/\\/g, '/').split('/');
115
+ valid(parts.every(p => p && p !== '.' && p !== '..' && !/[\x00-\x1f]/.test(p)));
116
+ let parent = '', original = '';
117
+ for (let i = 0; i < parts.length; i++) {
118
+ const name = parts[i].replace(/:/g, '_'), folder = i < parts.length - 1;
119
+ original += '/' + parts[i];
120
+ if (folder && folders.has(original)) { parent = folders.get(original); continue; }
121
+ const dot = !folder && name.lastIndexOf('.') > 0 ? name.lastIndexOf('.') : name.length;
122
+ const base = (parent + name).normalize('NFC').toLowerCase();
123
+ let candidate = parent + name, n = counters.get(base) || 1;
124
+ while (true) {
125
+ const key = candidate.normalize('NFC').toLowerCase(), prior = used.get(key);
126
+ if (prior === undefined || (folder && prior === 'folder')) {
127
+ used.set(key, folder ? 'folder' : 'file'); if (n > 1) counters.set(base, n); break;
128
+ }
129
+ candidate = parent + name.slice(0, dot) + ' (' + (++n) + ')' + name.slice(dot);
130
+ }
131
+ parent = candidate + (folder ? '/' : '');
132
+ if (folder) folders.set(original, parent);
133
+ }
134
+ return parent;
135
+ }
136
+
137
+ function headerLength(e, central) {
138
+ const extra = (e.size >= U32 ? 16 : 0) + (central && e.offset >= U32 ? 8 : 0);
139
+ return (central ? 46 : 30) + e.name.length + (extra ? 4 + extra : 0);
140
+ }
141
+ function header(e, central) {
142
+ const base = central ? 46 : 30, shift = central ? 2 : 0;
143
+ const bytes = new Uint8Array(headerLength(e, central)), d = view(bytes);
144
+ const extra = bytes.length - base - e.name.length;
145
+ d.setUint32(0, central ? 0x02014b50 : 0x04034b50, true);
146
+ if (central) d.setUint16(4, 45, true);
147
+ d.setUint16(4 + shift, extra ? 45 : 20, true);
148
+ d.setUint16(6 + shift, 0x0800, true);
149
+ d.setUint32(10 + shift, e.stamp, true);
150
+ d.setUint32(14 + shift, e.crc, true);
151
+ d.setUint32(18 + shift, Math.min(e.size, U32), true);
152
+ d.setUint32(22 + shift, Math.min(e.size, U32), true);
153
+ d.setUint16(26 + shift, e.name.length, true);
154
+ d.setUint16(28 + shift, extra, true);
155
+ if (central) d.setUint32(42, Math.min(e.offset, U32), true);
156
+ bytes.set(e.name, base);
157
+ if (extra) {
158
+ let at = base + e.name.length;
159
+ d.setUint16(at, 1, true); d.setUint16(at + 2, extra - 4, true); at += 4;
160
+ if (e.size >= U32) {
161
+ d.setBigUint64(at, BigInt(e.size), true); d.setBigUint64(at + 8, BigInt(e.size), true); at += 16;
162
+ }
163
+ if (central && e.offset >= U32) d.setBigUint64(at, BigInt(e.offset), true);
164
+ }
165
+ return bytes;
166
+ }
167
+ function ending(count, central, size) {
168
+ const large = count >= 65535 || central >= U32 || size >= U32;
169
+ const bytes = new Uint8Array(large ? 98 : 22), v = view(bytes), at = bytes.length - 22;
170
+ if (large) {
171
+ v.setUint32(0, 0x06064b50, true); v.setBigUint64(4, 44n, true);
172
+ v.setUint16(12, 45, true); v.setUint16(14, 45, true);
173
+ v.setBigUint64(24, BigInt(count), true); v.setBigUint64(32, BigInt(count), true);
174
+ v.setBigUint64(40, BigInt(size), true); v.setBigUint64(48, BigInt(central), true);
175
+ v.setUint32(56, 0x07064b50, true); v.setBigUint64(64, BigInt(central + size), true); v.setUint32(72, 1, true);
176
+ }
177
+ v.setUint32(at, 0x06054b50, true);
178
+ v.setUint16(at + 8, Math.min(count, 65535), true); v.setUint16(at + 10, Math.min(count, 65535), true);
179
+ v.setUint32(at + 12, Math.min(size, U32), true); v.setUint32(at + 16, Math.min(central, U32), true);
180
+ return bytes;
181
+ }
182
+
183
+ async function makePlan(io, sources) {
184
+ const used = new Map(), counters = new Map(), groups = [], cacheBudget = { remaining: 2 * 1024 * 1024 };
185
+ let offset = 0, count = 0, directorySize = 0;
186
+ for (const archive of sources) {
187
+ const source = { ...archive };
188
+ const entries = [], folders = new Map();
189
+ for await (const item of directory(io, source, cacheBudget)) {
190
+ const name = encoder.encode(uniquePath(item.path, used, folders, counters));
191
+ valid(name.length <= 65535);
192
+ const entry = { name, offset, size: item.size, input: item.input, stamp: item.stamp, crc: item.crc };
193
+ entries.push(entry); count++;
194
+ offset += headerLength(entry, false) + entry.size;
195
+ directorySize += headerLength(entry, true);
196
+ }
197
+ groups.push({ source, entries });
198
+ }
199
+ const end = ending(count, offset, directorySize), length = offset + directorySize + end.length;
200
+ valid(Number.isSafeInteger(length));
201
+ return { groups, central: offset, end, length };
202
+ }
203
+
204
+ function interval(value, length) {
205
+ const match = /^bytes=(\d*)-(\d*)$/i.exec(value);
206
+ if (!match || (!match[1] && !match[2])) return null;
207
+ const first = match[1] ? Number(match[1]) : Math.max(0, length - Number(match[2]));
208
+ const last = match[1] && match[2] ? Math.min(length - 1, Number(match[2])) : length - 1;
209
+ return Number.isSafeInteger(first) && Number.isSafeInteger(last) && first <= last ? [first, last] : null;
210
+ }
211
+
212
+ // Keep one reader per source and discard the old ZIP headers in between files.
213
+ async function* content(io, plan, first, last) {
214
+ for (const { source, entries } of plan.groups) {
215
+ const portions = [];
216
+ for (const e of entries) {
217
+ const data = e.offset + headerLength(e, false);
218
+ if (data + e.size <= first || e.offset > last) continue;
219
+ const lo = Math.max(first, data), hi = Math.min(last + 1, data + e.size);
220
+ portions.push({ e, data, lo: e.input + lo - data, hi: e.input + hi - data });
221
+ }
222
+ const payloads = portions.filter(p => p.lo < p.hi);
223
+ let cursor = payloads[0]?.lo, chunk, reader;
224
+ try {
225
+ for (const p of portions) {
226
+ if (p.e.offset <= last && p.data > first) {
227
+ yield header(p.e, false).subarray(Math.max(0, first - p.e.offset), last + 1 - p.e.offset);
228
+ }
229
+ if (p.lo >= p.hi) continue;
230
+ if (!reader) reader = (await storageRange(io, source, cursor, payloads.at(-1).hi - 1)).getReader();
231
+ while (cursor < p.hi) {
232
+ if (!chunk?.length) { const next = await reader.read(); valid(!next.done); chunk = next.value; }
233
+ const n = Math.min(chunk.length, p.hi - cursor);
234
+ if (cursor + n > p.lo) yield chunk.subarray(Math.max(0, p.lo - cursor), n);
235
+ chunk = chunk.subarray(n); cursor += n;
236
+ }
237
+ }
238
+ } finally { if (reader) await reader.cancel(); }
239
+ }
240
+ let offset = plan.central;
241
+ if (last >= offset) {
242
+ for (const { entries } of plan.groups) for (const e of entries) {
243
+ const size = headerLength(e, true);
244
+ if (offset > last) return;
245
+ if (offset + size > first) yield header(e, true).subarray(Math.max(0, first - offset), last + 1 - offset);
246
+ offset += size;
247
+ }
248
+ if (offset <= last) yield plan.end.subarray(Math.max(0, first - offset), last + 1 - offset);
249
+ }
250
+ }
251
+
252
+ export async function bundleResponse(request, sources, io, identity, disposition) {
253
+ const headers = new Headers({ 'Content-Type': 'application/zip', 'Content-Disposition': disposition,
254
+ 'Accept-Ranges': 'bytes', 'Cache-Control': 'private, no-store', 'X-Robots-Tag': 'noindex, nofollow',
255
+ 'ETag': '"' + identity + '"' });
256
+ let plan;
257
+ try { plan = await makePlan(io, sources); }
258
+ catch { return new Response('Archivio temporaneamente non disponibile. Riprova.', { status: 502,
259
+ headers: { 'Cache-Control': 'no-store', 'Content-Type': 'text/plain;charset=UTF-8' } }); }
260
+ const range = request.headers.get('Range'), validator = request.headers.get('If-Range');
261
+ const partial = !!range && (!validator || validator === headers.get('ETag'));
262
+ const span = partial ? interval(range, plan.length) : [0, plan.length - 1];
263
+ if (!span) { headers.set('Content-Range', 'bytes */' + plan.length); return new Response(null, { status: 416, headers }); }
264
+ const [first, last] = span, length = last - first + 1;
265
+ headers.set('Content-Length', String(length));
266
+ if (partial) headers.set('Content-Range', `bytes ${first}-${last}/${plan.length}`);
267
+ const init = { headers, status: partial ? 206 : 200 };
268
+ if (request.method === 'HEAD') return new Response(null, init);
269
+ const iterator = content(io, plan, first, last);
270
+ let stream = new ReadableStream({
271
+ async pull(controller) { const step = await iterator.next(); if (step.done) controller.close(); else controller.enqueue(step.value); },
272
+ cancel() { return iterator.return(); },
273
+ });
274
+ // workerd derives Content-Length from the stream itself.
275
+ if (typeof FixedLengthStream !== 'undefined') {
276
+ const fixed = new FixedLengthStream(length);
277
+ stream.pipeTo(fixed.writable).catch(() => {}); stream = fixed.readable;
278
+ }
279
+ return new Response(stream, init);
280
+ }