@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.
- package/dist/app/App.js +6 -6
- package/dist/app/app.css +110 -1
- package/dist/app/delivery.js +7 -7
- package/dist/app/guide/TransferGuide.js +1 -1
- package/dist/app/lib/deliveries.d.ts +6 -0
- package/dist/app/lib/delivery-capabilities.d.ts +31 -0
- package/dist/app/lib/delivery-capabilities.js +115 -0
- package/dist/app/lib/delivery-checkpoint-pipeline.d.ts +81 -0
- package/dist/app/lib/delivery-checkpoint-pipeline.js +195 -0
- package/dist/app/lib/delivery-finalize.d.ts +21 -0
- package/dist/app/lib/delivery-finalize.js +42 -0
- package/dist/app/lib/delivery-multipart-large.d.ts +18 -0
- package/dist/app/lib/delivery-multipart-large.js +28 -0
- package/dist/app/lib/delivery-network.d.ts +7 -1
- package/dist/app/lib/delivery-network.js +85 -18
- package/dist/app/lib/delivery-part-pipeline.d.ts +79 -0
- package/dist/app/lib/delivery-part-pipeline.js +270 -0
- package/dist/app/lib/delivery-upload-coordinator.d.ts +112 -0
- package/dist/app/lib/delivery-upload-coordinator.js +229 -0
- package/dist/app/lib/delivery-upload.d.ts +19 -3
- package/dist/app/lib/delivery-upload.js +226 -29
- package/dist/app/lib/upload-queue.d.ts +5 -0
- package/dist/app/lib/upload-queue.js +54 -29
- package/dist/app/routes/Deliveries.d.ts +9 -3
- package/dist/app/routes/Deliveries.js +318 -189
- package/dist/app/routes/DeliveryDashboard.js +1 -1
- package/dist/app/routes/DeliveryEmail.d.ts +8 -1
- package/dist/app/routes/DeliveryEmail.js +63 -23
- package/dist/app/routes/DeliveryRecipientPreview.d.ts +14 -0
- package/dist/app/routes/DeliveryRecipientPreview.js +49 -0
- package/dist/app/routes/Overview.js +5 -5
- package/dist/app/routes/UploadDock.js +4 -3
- package/dist/form/media/MediaGrid.js +1 -1
- package/dist/functions/_shared/b2.js +98 -19
- package/dist/functions/_shared/delivery-activation.js +98 -0
- package/dist/functions/_shared/delivery-download-bundle.js +280 -0
- package/dist/functions/_shared/delivery-email.js +92 -13
- package/dist/functions/_shared/delivery-file-names.js +19 -0
- package/dist/functions/_shared/delivery-finalization-paid.js +31 -0
- package/dist/functions/_shared/delivery-finalization-storage.js +64 -0
- package/dist/functions/_shared/delivery-manifest-free.js +74 -0
- package/dist/functions/_shared/delivery-manifest.js +277 -20
- package/dist/functions/_shared/delivery-multipart-verification.js +68 -0
- package/dist/functions/_shared/delivery-request.js +74 -0
- package/dist/functions/_shared/delivery-storage-access.js +14 -0
- package/dist/functions/_shared/delivery-upload-admission.js +221 -0
- package/dist/functions/_shared/delivery-upload-contract.js +44 -0
- package/dist/functions/_shared/delivery-upload-free.js +80 -0
- package/dist/functions/_shared/delivery-upload-policy.js +64 -0
- package/dist/functions/_shared/delivery-upload-session.js +365 -0
- package/dist/functions/_shared/delivery-work-budget.js +49 -0
- package/dist/functions/api/deliveries.js +58 -17
- package/dist/functions/api/delivery/multipart.js +152 -15
- package/dist/functions/delivery-public/assets/client.js +59 -54
- package/dist/functions/delivery-public/assets/delivery.css +6 -2
- package/dist/functions/delivery-public/index.js +43 -15
- package/dist/functions/delivery-public/migrations/0015_delivery_activation_intents.sql +12 -0
- package/dist/functions/delivery-public/migrations/0016_delivery_multipart_verification.sql +16 -0
- package/dist/functions/delivery-public/migrations/0017_delivery_upload_admission.sql +38 -0
- package/dist/functions/delivery-public/migrations/0018_delivery_upload_sessions.sql +26 -0
- package/dist/functions/delivery-public/migrations/0019_delivery_manifest_fragments.sql +27 -0
- package/dist/functions/delivery-public/migrations/0020_delivery_email_reply_to.sql +1 -0
- package/dist/functions/index.js +3 -1
- package/dist/theme.css +2 -1
- package/package.json +1 -1
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* Access/JWT/origin checks. Cron drains only explicitly queued notifications. */
|
|
3
3
|
import {seal,unseal,sha256} from './delivery-crypto.js';
|
|
4
4
|
import {deliveryEmailProvider,deliveryEmailProviderConfigured,sendCloudflareDeliveryEmail} from './delivery-email-provider.js';
|
|
5
|
+
import {COMMON_FINALIZATION_ROLLOUT_ENABLED,rejectDisabledUploadPipeline} from './delivery-upload-policy.js';
|
|
6
|
+
import {readDeliveryJson,deliveryBodyErrorResponse,DeliveryBodyError} from './delivery-request.js';
|
|
5
7
|
const headers={'Content-Type':'application/json','Cache-Control':'private, no-store','X-Robots-Tag':'noindex, nofollow'};
|
|
6
8
|
const json=(body,status=200)=>new Response(JSON.stringify(body),{status,headers});
|
|
7
9
|
const fail=(text,status=400)=>Object.assign(new Error(text),{status});
|
|
@@ -30,21 +32,31 @@ export async function saveDeliveryEmailSettings(env,body){
|
|
|
30
32
|
return deliveryEmailConfiguration(env);
|
|
31
33
|
}
|
|
32
34
|
async function installed(env){return !!env.DB&&!!await env.DB.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='delivery_email_outbox'").first();}
|
|
35
|
+
async function emailFormConfiguration(env) {
|
|
36
|
+
const config = await deliveryEmailConfiguration(env);
|
|
37
|
+
const replyToEditable = !!env.DB && !!await env.DB.prepare("SELECT name FROM pragma_table_info('delivery_email_preferences') WHERE name='reply_to_email'").first();
|
|
38
|
+
return {...config, replyToEditable};
|
|
39
|
+
}
|
|
33
40
|
async function delivery(env,id){const d=await env.DB.prepare("SELECT * FROM deliveries WHERE id=? AND status!='deleted'").bind(id).first();if(!d)throw fail('Transfer non trovato',404);return d;}
|
|
34
41
|
async function prefs(env,id){return await env.DB.prepare('SELECT * FROM delivery_email_preferences WHERE delivery_id=?').bind(id).first()||{recipient_email:'',notify_owner:0,send_recipient:0};}
|
|
35
42
|
export async function readDeliveryEmailState(env,id){
|
|
36
|
-
const config=
|
|
43
|
+
const config=await emailFormConfiguration(env);if(!await installed(env))return {configuration:{...config,enabled:false,ownerEnabled:false},preferences:{recipientEmail:'',notifyOwner:false,sendRecipient:false},messages:[],migrationRequired:true};
|
|
37
44
|
await delivery(env,id);const p=await prefs(env,id);const {results}=await env.DB.prepare('SELECT id,kind,recipient,state,attempts,created_at,sent_at,error_code,generation FROM delivery_email_outbox WHERE delivery_id=? ORDER BY created_at DESC,id LIMIT 20').bind(id).all();
|
|
38
|
-
return {configuration:config,preferences:{recipientEmail:p.recipient_email,notifyOwner:!!p.notify_owner,sendRecipient:!!p.send_recipient},messages:(results||[]).map(r=>({id:r.id,kind:r.kind,recipient:r.recipient,state:r.state,attempts:r.attempts,createdAt:r.created_at,sentAt:r.sent_at,errorCode:r.error_code,reason:r.generation.startsWith('download:')?'download':'ready'}))};
|
|
45
|
+
return {configuration:config,preferences:{recipientEmail:p.recipient_email,...(p.reply_to_email ? {replyToEmail:p.reply_to_email} : {}),notifyOwner:!!p.notify_owner,sendRecipient:!!p.send_recipient},messages:(results||[]).map(r=>({id:r.id,kind:r.kind,recipient:r.recipient,state:r.state,attempts:r.attempts,createdAt:r.created_at,sentAt:r.sent_at,errorCode:r.error_code,reason:r.generation.startsWith('download:')?'download':'ready'}))};
|
|
39
46
|
}
|
|
40
47
|
export async function saveDeliveryEmailPreferences(env,id,body){
|
|
41
48
|
await delivery(env,id);if(!await installed(env))throw fail('Aggiornamento del servizio email necessario',503);
|
|
42
49
|
const recipient=address(body.recipientEmail);if(recipient&&!validDeliveryEmail(recipient))throw fail('Inserisci un indirizzo email valido');
|
|
43
50
|
const config=(await deliveryEmailConfiguration(env));if(body.sendRecipient&&!config.enabled)throw fail('Il servizio email non è ancora configurato',409);
|
|
44
51
|
if(body.sendRecipient&&!recipient)throw fail('Inserisci l’email del destinatario');
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
52
|
+
const hasReplyTo = body.replyToEmail !== undefined;
|
|
53
|
+
const replyTo = address(body.replyToEmail);
|
|
54
|
+
if(hasReplyTo && replyTo && !validDeliveryEmail(replyTo))throw fail('Inserisci un indirizzo email valido per il mittente');
|
|
55
|
+
if(hasReplyTo && !(await emailFormConfiguration(env)).replyToEditable)throw fail('Aggiorna il servizio per modificare il mittente',409);
|
|
56
|
+
const column = hasReplyTo ? ',reply_to_email' : '';
|
|
57
|
+
await env.DB.prepare(`INSERT INTO delivery_email_preferences(delivery_id,recipient_email,notify_owner,send_recipient,updated_at${column}) VALUES (?,?,?,?,?${hasReplyTo?',?':''})
|
|
58
|
+
ON CONFLICT(delivery_id) DO UPDATE SET recipient_email=excluded.recipient_email,notify_owner=excluded.notify_owner,send_recipient=excluded.send_recipient,updated_at=excluded.updated_at${hasReplyTo?',reply_to_email=excluded.reply_to_email':''}`)
|
|
59
|
+
.bind(id,recipient,Number(body.notifyOwner===true),Number(body.sendRecipient===true),new Date().toISOString(),...(hasReplyTo?[replyTo]:[])).run();
|
|
48
60
|
// Stop pending messages whose consent/address changed, including claimed jobs.
|
|
49
61
|
await env.DB.prepare(`UPDATE delivery_email_outbox SET state='cancelled',lease_token=NULL,lease_until=NULL WHERE delivery_id=? AND state IN ('pending','sending')
|
|
50
62
|
AND (kind='recipient' AND (?=0 OR recipient!=?))`).bind(id,Number(body.sendRecipient===true),recipient).run();
|
|
@@ -66,16 +78,17 @@ async function message(env,s,kind,recipient,token,providedConfig=null){
|
|
|
66
78
|
const esc=v=>String(v).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
67
79
|
return {from:`${brand.replace(/[<>]/g,'')} <${config.fromEmail}>`,to:[recipient],...(config.ownerEmail?{reply_to:config.ownerEmail}:{}),subject:`${kind==='owner'?'Caricamento completato':'I tuoi file sono pronti'} · ${title}`,text,html:`<div style="font-family:system-ui,sans-serif;max-width:600px;margin:auto;line-height:1.6"><h1 style="font-size:24px">${esc(intro)}</h1><h2 style="font-size:20px">${esc(title)}</h2><p style="white-space:pre-line">${esc(kind==='recipient'?s.d.description||'':'')}</p><p><a href="${esc(url)}" style="display:inline-block;padding:12px 20px;background:#166b57;color:white;border-radius:8px;text-decoration:none">Apri il transfer</a></p><p>${esc(expiry)}</p>${s.link.pin_ciphertext?'<p>È richiesto un codice di accesso, da chiedere al mittente.</p>':''}<p>${esc(brand)}</p></div>`};
|
|
68
80
|
}
|
|
69
|
-
export async function queueDeliveryEmails(env,id,{kind=null,resend=false}={}){
|
|
81
|
+
export async function queueDeliveryEmails(env,id,{kind=null,resend=false,intended=null}={}){
|
|
70
82
|
if(!(await deliveryEmailConfiguration(env)).enabled||!await installed(env))return [];
|
|
71
|
-
const s=await snapshot(env,id);if(!s)return [];const p=await prefs(env,id),c=(await deliveryEmailConfiguration(env)),targets=[];
|
|
83
|
+
const s=await snapshot(env,id);if(!s||intended&&(s.generation!==intended.generation||s.link.id!==intended.linkId))return [];const p=await prefs(env,id),c=(await deliveryEmailConfiguration(env)),targets=[];
|
|
72
84
|
if(c.notifyReady&&c.ownerEnabled&&(!kind||kind==='owner'))targets.push(['owner',c.ownerEmail]);
|
|
73
85
|
if(p.send_recipient&&validDeliveryEmail(p.recipient_email)&&(!kind||kind==='recipient'))targets.push(['recipient',p.recipient_email]);
|
|
74
86
|
const now=new Date().toISOString(),ids=[];
|
|
75
87
|
for(const [type,to]of targets){
|
|
88
|
+
if(intended&&!intended.targets.some(t=>t.kind===type&&t.recipient===to))continue;
|
|
76
89
|
if(resend){const recent=await env.DB.prepare('SELECT COUNT(*) n,MAX(created_at) last FROM delivery_email_outbox WHERE delivery_id=? AND kind=? AND created_at>?').bind(id,type,new Date(Date.now()-86400000).toISOString()).first();if(recent.n>=5||recent.last&&Date.now()-Date.parse(recent.last)<60000)throw fail('Attendi prima di inviare nuovamente l’email',429);}
|
|
77
90
|
const key=resend?crypto.randomUUID():await sha256(`${id}/${s.generation}/${type}/${to}`),token=await unseal(env.DELIVERY_SECRET,s.link.token_ciphertext);
|
|
78
|
-
const payload=await message(env,s,type,to,token,c),cipher=await seal(env.DELIVERY_SECRET,JSON.stringify(payload));
|
|
91
|
+
const payload=await message(env,s,type,to,token,type==='recipient' && p.reply_to_email ? {...c,ownerEmail:p.reply_to_email} : c),cipher=await seal(env.DELIVERY_SECRET,JSON.stringify(payload));
|
|
79
92
|
const sql=`INSERT OR IGNORE INTO delivery_email_outbox(id,delivery_id,kind,recipient,payload_ciphertext,created_at,next_attempt_at,link_id,generation) SELECT ?,?,?,?,?,?,?,?,?`;
|
|
80
93
|
const values=[key,id,type,to,cipher,now,now,s.link.id,s.generation];
|
|
81
94
|
const guard=resend?` WHERE NOT EXISTS (SELECT 1 FROM delivery_email_outbox WHERE delivery_id=? AND kind=? AND created_at>?) AND (SELECT COUNT(*) FROM delivery_email_outbox WHERE delivery_id=? AND kind=? AND created_at>?)<5`:'';
|
|
@@ -99,7 +112,9 @@ export async function queueDownloadNotifications(env){
|
|
|
99
112
|
const id=await sha256('download/'+event.id+'/'+c.ownerEmail),token=await unseal(env.DELIVERY_SECRET,s.link.token_ciphertext);
|
|
100
113
|
const payload=await message(env,s,'owner',c.ownerEmail,token,c),date=new Date(event.created_at).toLocaleString('it-IT',{timeZone:'Europe/Rome'});
|
|
101
114
|
payload.subject='Download richiesto · '+String(s.d.title||'Transfer').slice(0,180).replace(/[\r\n]/g,' ');
|
|
102
|
-
|
|
115
|
+
const version=event.variant==='web'?'Versione leggera':event.variant==='available'?'File disponibili':'Originali';
|
|
116
|
+
const url=new URL('/c/'+encodeURIComponent(token),env.DELIVERY_PUBLIC_BASE).href;
|
|
117
|
+
payload.text=`È stato avviato il download di «${s.d.title}».\n${date} · ${version}\n\nApri il transfer: ${url}`;
|
|
103
118
|
// Text-only avoids implying upload completion in the ready template.
|
|
104
119
|
delete payload.html;
|
|
105
120
|
const now=new Date().toISOString();await env.DB.prepare(`INSERT OR IGNORE INTO delivery_email_outbox(id,delivery_id,kind,recipient,payload_ciphertext,created_at,next_attempt_at,link_id,generation)
|
|
@@ -109,7 +124,8 @@ export async function queueDownloadNotifications(env){
|
|
|
109
124
|
}
|
|
110
125
|
if(cursor>settings.last_download_event)await env.DB.prepare('UPDATE delivery_email_settings SET last_download_event=? WHERE singleton=1 AND version=? AND last_download_event<?').bind(cursor,c.settingsVersion,cursor).run();
|
|
111
126
|
}
|
|
112
|
-
export async function processDeliveryEmails(env,{limit=2,fetch:send=globalThis.fetch,email,timeoutMs}={}){
|
|
127
|
+
export async function processDeliveryEmails(env,{limit=2,fetch:send=globalThis.fetch,email,timeoutMs,prepareReadyIntents=COMMON_FINALIZATION_ROLLOUT_ENABLED}={}){
|
|
128
|
+
if(prepareReadyIntents)await processDeliveryReadyIntents(env,{limit});
|
|
113
129
|
if(env.DELIVERY_EMAIL_ENABLED!=='true')return;
|
|
114
130
|
const provider=deliveryEmailProvider(env);
|
|
115
131
|
// Local/staging callers must explicitly inject a test binding. A remote binding
|
|
@@ -144,12 +160,75 @@ export async function processDeliveryEmails(env,{limit=2,fetch:send=globalThis.f
|
|
|
144
160
|
async function finish(state,providerId,code){const attempts=job.attempts+1;if(state==='pending'&&attempts>=8)state='review';await env.DB.prepare(`UPDATE delivery_email_outbox SET state=?,provider_id=?,error_code=?,sent_at=?,next_attempt_at=?,lease_until=NULL,lease_token=NULL WHERE id=? AND lease_token=? AND state='sending'`).bind(state,providerId,code,state==='sent'?new Date().toISOString():null,new Date(Date.now()+Math.min(3600000,60000*2**Math.min(attempts,6))).toISOString(),job.id,claim).run();}
|
|
145
161
|
}
|
|
146
162
|
}
|
|
147
|
-
|
|
148
|
-
|
|
163
|
+
// Capture only server-side recipients and a publication-time consent guard.
|
|
164
|
+
// No token, link URL or prepared message is needed in the activation response.
|
|
165
|
+
export async function captureReadyNotificationPolicy(env,id){
|
|
166
|
+
const c=await deliveryEmailConfiguration(env),targets=[];
|
|
167
|
+
if(!c.enabled)return {targets,guard:'1',args:[]};
|
|
168
|
+
if(!await installed(env))throw fail('Aggiornamento notifiche necessario',503);
|
|
169
|
+
const p=await prefs(env,id);
|
|
170
|
+
if(c.notifyReady&&c.ownerEnabled)targets.push({kind:'owner',recipient:c.ownerEmail});
|
|
171
|
+
if(p.send_recipient&&validDeliveryEmail(p.recipient_email))targets.push({kind:'recipient',recipient:p.recipient_email});
|
|
172
|
+
const settings=c.settingsEditable?'COALESCE((SELECT version FROM delivery_email_settings WHERE singleton=1),0)=?':'1';
|
|
173
|
+
return {targets,guard:`${settings}
|
|
174
|
+
AND COALESCE((SELECT recipient_email FROM delivery_email_preferences WHERE delivery_id=?),'')=?
|
|
175
|
+
AND COALESCE((SELECT send_recipient FROM delivery_email_preferences WHERE delivery_id=?),0)=?
|
|
176
|
+
AND COALESCE((SELECT updated_at FROM delivery_email_preferences WHERE delivery_id=?),'')=?`,
|
|
177
|
+
args:[...(c.settingsEditable?[c.settingsVersion]:[]),id,p.recipient_email,id,p.send_recipient,id,p.updated_at||'']};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Intents are created atomically with activation. Preparation is idempotent:
|
|
181
|
+
// an interrupted run reuses the existing generation/kind/recipient outbox IDs.
|
|
182
|
+
export async function processDeliveryReadyIntents(env,{limit=2}={}){
|
|
183
|
+
const installed=await env.DB.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='delivery_activation_intents'").first();
|
|
184
|
+
if(!installed)return;
|
|
185
|
+
const now=new Date().toISOString();
|
|
186
|
+
const jobs=(await env.DB.prepare(`SELECT * FROM delivery_activation_intents WHERE
|
|
187
|
+
(state='pending' AND next_attempt_at<=?) OR (state='preparing' AND lease_until<=?) ORDER BY created_at,delivery_id LIMIT ?`)
|
|
188
|
+
.bind(now,now,Math.max(1,Math.min(Number(limit)||1,2))).all()).results||[];
|
|
189
|
+
for(const job of jobs){
|
|
190
|
+
const token=crypto.randomUUID();
|
|
191
|
+
const claim=await env.DB.prepare(`UPDATE delivery_activation_intents SET state='preparing',lease_token=?,lease_until=?,attempts=attempts+1
|
|
192
|
+
WHERE delivery_id=? AND generation=? AND ((state='pending' AND next_attempt_at<=?) OR (state='preparing' AND lease_until<=?))`)
|
|
193
|
+
.bind(token,new Date(Date.now()+120000).toISOString(),job.delivery_id,job.generation,now,now).run();
|
|
194
|
+
if(!claim.meta.changes)continue;
|
|
195
|
+
const finish=(state,code)=>env.DB.prepare(`UPDATE delivery_activation_intents SET state=?,error_code=?,next_attempt_at=?,lease_token=NULL,lease_until=NULL,
|
|
196
|
+
attempts=CASE WHEN ?='awaiting_packages' THEN 0 ELSE attempts END
|
|
197
|
+
WHERE delivery_id=? AND generation=? AND state='preparing' AND lease_token=?`)
|
|
198
|
+
.bind(state,code,new Date(Date.now()+60000).toISOString(),code,job.delivery_id,job.generation,token).run();
|
|
199
|
+
try{
|
|
200
|
+
const targets=JSON.parse(job.policy_json);
|
|
201
|
+
if(!Array.isArray(targets)||targets.length>2||targets.some(t=>!['owner','recipient'].includes(t.kind)||!validDeliveryEmail(t.recipient)))throw Error('Invalid notification policy');
|
|
202
|
+
if(!targets.length){await finish('prepared','no_notifications');continue;}
|
|
203
|
+
const s=await snapshot(env,job.delivery_id);
|
|
204
|
+
if(!s){
|
|
205
|
+
const d=await env.DB.prepare(`SELECT id FROM deliveries WHERE id=? AND status='active'
|
|
206
|
+
AND (files_expires_at IS NULL OR files_expires_at>?) AND (expires_at IS NULL OR expires_at>?)`).bind(job.delivery_id,now,now).first();
|
|
207
|
+
const live=(await env.DB.prepare("SELECT id,state FROM delivery_packages WHERE delivery_id=? AND state!='deleted' ORDER BY id").bind(job.delivery_id).all()).results||[];
|
|
208
|
+
const link=await env.DB.prepare('SELECT id FROM delivery_links WHERE id=? AND delivery_id=? AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at>?)').bind(job.link_id,job.delivery_id,now).first();
|
|
209
|
+
if(d&&link&&JSON.stringify(live.map(p=>p.id))===job.packages_json&&live.some(p=>p.state==='uploading'))await finish('pending','awaiting_packages');
|
|
210
|
+
else await finish('cancelled','availability_changed');
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
if(s.generation!==job.generation||s.link.id!==job.link_id){await finish('cancelled','availability_changed');continue;}
|
|
214
|
+
if(!(await deliveryEmailConfiguration(env)).enabled){await finish('cancelled','service_disabled');continue;}
|
|
215
|
+
await queueDeliveryEmails(env,job.delivery_id,{intended:{generation:job.generation,linkId:job.link_id,targets}});
|
|
216
|
+
await finish('prepared',null);
|
|
217
|
+
}catch{
|
|
218
|
+
await finish(job.attempts+1>=8?'review':'pending','preparation_retryable');
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
export async function handleDeliveryEmailRequest(request,env,parsed){
|
|
223
|
+
const url=new URL(request.url);let body=null;if(request.method==='POST'){
|
|
224
|
+
const headerRejection=rejectDisabledUploadPipeline(request);if(headerRejection)return headerRejection;
|
|
225
|
+
if(parsed&&Object.hasOwn(parsed,'body'))body=parsed.body;else{try{body=await readDeliveryJson(request.clone());}catch(e){if(e instanceof DeliveryBodyError&&e.status===413)return deliveryBodyErrorResponse(e);return null;}}
|
|
226
|
+
const pipelineRejection=rejectDisabledUploadPipeline(request,body);if(pipelineRejection)return pipelineRejection;
|
|
227
|
+
}
|
|
149
228
|
if(!(request.method==='GET'&&url.searchParams.get('email')==='1')&&!['emailSettings','emailPreferences','emailSend'].includes(body?.action))return null;
|
|
150
229
|
try{
|
|
151
230
|
if(body?.action==='emailSettings')return json({ok:true,email:{configuration:await saveDeliveryEmailSettings(env,body)}});
|
|
152
|
-
const id=address(body?.id||url.searchParams.get('id'));if(request.method==='GET'&&!id)return json({ok:true,email:{configuration:await installed(env)?(await
|
|
231
|
+
const id=address(body?.id||url.searchParams.get('id'));if(request.method==='GET'&&!id)return json({ok:true,email:{configuration:await installed(env)?(await emailFormConfiguration(env)):{...(await deliveryEmailConfiguration(env)),enabled:false,ownerEnabled:false},preferences:{recipientEmail:'',notifyOwner:false,sendRecipient:false},messages:[]}});if(!id||id.length>100)throw fail('Transfer non valido');
|
|
153
232
|
if(request.method==='GET')return json({ok:true,email:await readDeliveryEmailState(env,id)});
|
|
154
233
|
if(body.action==='emailPreferences')return json({ok:true,email:await saveDeliveryEmailPreferences(env,id,body)});
|
|
155
234
|
if(!['owner','recipient'].includes(body.kind))throw fail('Destinatario non valido');
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Page the original ZIP paths without reading file bytes or gallery metadata. */
|
|
2
|
+
export async function fileNamePage(env, pkg, after = -1, limit = 50) {
|
|
3
|
+
if (!Number.isSafeInteger(after) || after < -1 || !Number.isSafeInteger(limit) || limit < 1 || limit > 50) {
|
|
4
|
+
throw Object.assign(new Error("Pagina non valida"), { status: 400 });
|
|
5
|
+
}
|
|
6
|
+
let manifest;
|
|
7
|
+
try { manifest = JSON.parse(pkg.manifest_json || "{}"); } catch { manifest = {}; }
|
|
8
|
+
if (manifest?.version !== 2) {
|
|
9
|
+
const entries = manifest?.entries || [];
|
|
10
|
+
const end = Math.min(entries.length, after + 1 + limit);
|
|
11
|
+
return { names: entries.slice(after + 1, end).map(entry => entry.name), nextCursor: end < entries.length ? end - 1 : null };
|
|
12
|
+
}
|
|
13
|
+
const { results } = await env.DB.prepare(`
|
|
14
|
+
SELECT entry_id, name FROM delivery_manifest_entries
|
|
15
|
+
WHERE package_id=? AND entry_id>? ORDER BY entry_id LIMIT ?
|
|
16
|
+
`).bind(pkg.id, after, limit + 1).all();
|
|
17
|
+
const page = results.slice(0, limit);
|
|
18
|
+
return { names: page.map(row => row.name), nextCursor: results.length > limit ? page.at(-1).entry_id : null };
|
|
19
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { finalizeManifestStepCommon } from './delivery-manifest.js';
|
|
2
|
+
import { createDeliveryWorkBudget, requirePaidUpload } from './delivery-work-budget.js';
|
|
3
|
+
|
|
4
|
+
// Only pages are coalesced. Seal, root and activation keep their own requests.
|
|
5
|
+
// Every completed page commits its own durable cursor before the next starts.
|
|
6
|
+
export async function finalizeManifestPaid(env, body, { trace, now } = {}) {
|
|
7
|
+
requirePaidUpload(env);
|
|
8
|
+
const scoped = createDeliveryWorkBudget(env, now), work = scoped.budget;
|
|
9
|
+
let result, stopReason;
|
|
10
|
+
for (;;) {
|
|
11
|
+
requirePaidUpload(env); // Never infer Paid from a client flag or a binding.
|
|
12
|
+
const state = await scoped.env.DB.prepare(`SELECT s.state,s.cursor,p.file_count FROM delivery_manifest_state s
|
|
13
|
+
JOIN delivery_packages p ON p.id=s.package_id WHERE p.id=? AND p.delivery_id=?`)
|
|
14
|
+
.bind(String(body.packageId || ''), String(body.id || '')).first();
|
|
15
|
+
// One common invocation handles an initial seal or a final root. Never
|
|
16
|
+
// append either to a batch of pages, even when there is remaining budget.
|
|
17
|
+
if (result && (state?.state !== 'sealed' || state.cursor >= state.file_count)) { stopReason = 'boundary'; break; }
|
|
18
|
+
stopReason = work.stopReason();
|
|
19
|
+
if (stopReason && result) break;
|
|
20
|
+
const step = await finalizeManifestStepCommon(scoped.env, body, trace, work);
|
|
21
|
+
if (step.budgetStopped) { result = step; stopReason = 'metadata'; break; }
|
|
22
|
+
work.used.units++;
|
|
23
|
+
if (result && step.cursor <= result.cursor) throw new Error('La finalizzazione Paid non avanza');
|
|
24
|
+
result = step;
|
|
25
|
+
if (step.phase !== 'pages') { stopReason = 'boundary'; break; }
|
|
26
|
+
stopReason = work.stopReason();
|
|
27
|
+
if (stopReason) break;
|
|
28
|
+
}
|
|
29
|
+
const { budgetStopped, ...step } = result;
|
|
30
|
+
return { ...step, units: work.used.units, stopReason, work: { ...work.used } };
|
|
31
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { b2ControlRequest, b2PutSmall, b2Head } from './b2.js';
|
|
2
|
+
import { sha256 } from './delivery-crypto.js';
|
|
3
|
+
import { freeWork,needsPaid } from './delivery-upload-free.js';
|
|
4
|
+
const LIMIT = 256 * 1024;
|
|
5
|
+
const fail = (message, status = 409) => Object.assign(new Error(message), { status, code: 'delivery_manifest', retryable: status >= 500 });
|
|
6
|
+
|
|
7
|
+
export async function measureFinalization(trace, stage, operation) {
|
|
8
|
+
if (!trace) return operation();
|
|
9
|
+
const started = performance.now();
|
|
10
|
+
try { return await operation(); }
|
|
11
|
+
finally { try { trace({ stage, wallMs: performance.now() - started }); } catch {} }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// A successful PUT of the known immutable body is the same proof used by the
|
|
15
|
+
// existing path. After an uncertain write, GET + SHA-256 recognizes that exact
|
|
16
|
+
// object instead of creating another version. Never overwrite a conflicting key.
|
|
17
|
+
export async function ensureManifestObject(env, key, json, newlyReserved) {
|
|
18
|
+
const expectedBytes = new TextEncoder().encode(json).length;
|
|
19
|
+
if (expectedBytes > LIMIT) throw fail('Oggetto manifest troppo grande', 413);
|
|
20
|
+
if(freeWork(env)&&!freeWork(env).canRead(expectedBytes))throw needsPaid();
|
|
21
|
+
if (!newlyReserved) {
|
|
22
|
+
const response = await b2ControlRequest(env, 'GET', key, { signal: AbortSignal.timeout(60_000) });
|
|
23
|
+
if (response.status !== 404) {
|
|
24
|
+
if (!response.ok) { await response.body?.cancel(); throw fail('Verifica oggetto temporaneamente non disponibile', 502); }
|
|
25
|
+
if (Number(response.headers.get('content-length')) > LIMIT) { await response.body?.cancel(); throw fail('Oggetto manifest remoto troppo grande'); }
|
|
26
|
+
const reader = response.body?.getReader(), chunks = [];
|
|
27
|
+
let size = 0;
|
|
28
|
+
try {
|
|
29
|
+
if (!reader) throw fail('Oggetto manifest remoto vuoto');
|
|
30
|
+
for (;;) {
|
|
31
|
+
const { value, done } = await reader.read(); if (done) break;
|
|
32
|
+
size += value.length;
|
|
33
|
+
if (size > LIMIT || size > expectedBytes) throw fail('Dimensione oggetto manifest diversa');
|
|
34
|
+
chunks.push(value);
|
|
35
|
+
}
|
|
36
|
+
} finally { await reader?.cancel(); }
|
|
37
|
+
const data = new Uint8Array(size); let at = 0;
|
|
38
|
+
freeWork(env)?.readBytes(size);
|
|
39
|
+
for (const chunk of chunks) { data.set(chunk, at); at += chunk.length; }
|
|
40
|
+
const actual = [...new Uint8Array(await crypto.subtle.digest('SHA-256', data))].map(n => n.toString(16).padStart(2, '0')).join('');
|
|
41
|
+
if (size !== expectedBytes || actual !== await sha256(json)) throw fail('Oggetto manifest remoto in conflitto');
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
await response.body?.cancel();
|
|
45
|
+
}
|
|
46
|
+
await b2PutSmall(env, key, json, 'application/json');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function verifyArchiveHeads(env, uploads) {
|
|
50
|
+
const heads = new Map(); let index = 0, failure;
|
|
51
|
+
const worker = async () => {
|
|
52
|
+
while (!failure && index < uploads.length) {
|
|
53
|
+
const upload = uploads[index++];
|
|
54
|
+
try {
|
|
55
|
+
const head = await b2Head(env, upload.object_key);
|
|
56
|
+
if (!head || head.bytes !== upload.bytes) throw fail('Dimensione remota diversa dall’archivio completato');
|
|
57
|
+
heads.set(upload.variant, { key: upload.object_key, bytes: upload.bytes, etag: head.etag });
|
|
58
|
+
} catch (error) { failure ??= error; }
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
await Promise.allSettled(Array.from({ length: Math.min(2, uploads.length) }, worker));
|
|
62
|
+
if (failure) throw failure;
|
|
63
|
+
return Object.fromEntries(uploads.map(u => [u.variant, heads.get(u.variant)]));
|
|
64
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { sha256 } from './delivery-crypto.js';
|
|
2
|
+
import { FREE_UPLOAD_UNIT,freeWork,needsPaid } from './delivery-upload-free.js';
|
|
3
|
+
import { uploadSessionSequence,uploadSessionError } from './delivery-upload-contract.js';
|
|
4
|
+
const bytes=s=>new TextEncoder().encode(s).length;
|
|
5
|
+
const conflict=()=>uploadSessionError('delivery_manifest','Preparazione del manifest cambiata o incompleta');
|
|
6
|
+
|
|
7
|
+
// Private durable micro-reads, separate from the existing logical pages. The
|
|
8
|
+
// final emitter still recomputes the full page and all original proofs. A large
|
|
9
|
+
// indivisible emit explicitly requires Paid; preparation is not authorization.
|
|
10
|
+
export async function prepareFreeManifestPage(env,pkg,state,prior,byVariant,body) {
|
|
11
|
+
if(!freeWork(env))return null;
|
|
12
|
+
const sequence=uploadSessionSequence(env);
|
|
13
|
+
if(!Number.isSafeInteger(sequence))throw conflict();
|
|
14
|
+
let work=await env.DB.prepare('SELECT * FROM delivery_manifest_read_work WHERE package_id=? AND page_number=?')
|
|
15
|
+
.bind(pkg.id,state.page_count).first();
|
|
16
|
+
if(work?.start_cursor!==undefined&&work.start_cursor!==state.cursor)throw conflict();
|
|
17
|
+
if(work&&work.last_sequence>sequence)throw conflict();
|
|
18
|
+
if(work?.last_sequence===sequence)return JSON.parse(work.last_result);
|
|
19
|
+
if(work?.prepared){
|
|
20
|
+
if(work.entry_count>32||work.wire_bytes>FREE_UPLOAD_UNIT.dataBytes||!freeWork(env).canRead(work.wire_bytes))throw needsPaid();
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
work??={start_cursor:state.cursor,read_cursor:state.cursor,entry_count:0,packed_bytes:128,wire_bytes:0,chain:'',last_sequence:-1};
|
|
24
|
+
const sizes=(await env.DB.prepare(`SELECT entry_id,length(CAST(entry_json AS BLOB)) bytes,
|
|
25
|
+
length(CAST(json_object('entry_id',entry_id,'entry_json',entry_json) AS BLOB))+1 wire_bytes
|
|
26
|
+
FROM delivery_manifest_entries WHERE package_id=? AND entry_id>=? ORDER BY entry_id LIMIT 32`)
|
|
27
|
+
.bind(pkg.id,work.read_cursor).all()).results||[];
|
|
28
|
+
let packed=work.packed_bytes,wire=2,prepared=false;
|
|
29
|
+
const selected=[];
|
|
30
|
+
for(const row of sizes){
|
|
31
|
+
if(row.entry_id!==work.read_cursor+selected.length)throw conflict();
|
|
32
|
+
const count=work.entry_count+selected.length;
|
|
33
|
+
if(count===200||prior&&row.entry_id>=prior.end_cursor){prepared=true;break;}
|
|
34
|
+
const n=row.bytes+bytes('{"index":'+row.entry_id+',"entry":}')+1;
|
|
35
|
+
if(packed+n>262144){if(prior)throw conflict();prepared=true;break;}
|
|
36
|
+
if(wire+row.wire_bytes>FREE_UPLOAD_UNIT.dataBytes){if(!selected.length)throw needsPaid();break;}
|
|
37
|
+
selected.push(row.entry_id);packed+=n;wire+=row.wire_bytes;
|
|
38
|
+
}
|
|
39
|
+
const end=work.read_cursor+selected.length,count=work.entry_count+selected.length;
|
|
40
|
+
if(end===pkg.file_count||count===200||prior&&end===prior.end_cursor)prepared=true;
|
|
41
|
+
if(!selected.length&&!prepared)throw conflict();
|
|
42
|
+
if(prior&&prepared&&(count!==prior.entry_count||end!==prior.end_cursor))throw conflict();
|
|
43
|
+
if(!freeWork(env).canRead(wire))throw needsPaid();
|
|
44
|
+
const rows=selected.length?(await env.DB.prepare(`SELECT entry_id,entry_json FROM delivery_manifest_entries
|
|
45
|
+
WHERE package_id=? AND entry_id>=? AND entry_id<? ORDER BY entry_id LIMIT 32`).bind(pkg.id,work.read_cursor,end).all()).results||[]:[];
|
|
46
|
+
if(rows.length!==selected.length||rows.some((r,i)=>r.entry_id!==selected[i]))throw conflict();
|
|
47
|
+
for(const row of rows)for(const [kind,field]of[['originals','original'],['web','web'],['thumbs','thumb']]){
|
|
48
|
+
const m=JSON.parse(row.entry_json)[field];
|
|
49
|
+
if(m&&(!byVariant[kind]||m.offset+m.length>byVariant[kind].bytes))throw conflict();
|
|
50
|
+
}
|
|
51
|
+
const json=JSON.stringify(rows),digest=await sha256(json),chain=await sha256(JSON.stringify([work.chain,work.read_cursor,end,digest]));
|
|
52
|
+
const result={done:false,phase:'preparing',cursor:state.cursor,total:pkg.file_count,workCursor:end,prepared};
|
|
53
|
+
const fence=`EXISTS(SELECT 1 FROM delivery_packages p JOIN delivery_manifest_state s ON s.package_id=p.id
|
|
54
|
+
JOIN deliveries d ON d.id=p.delivery_id WHERE p.id=? AND p.state='uploading' AND s.state='sealed'
|
|
55
|
+
AND s.writer_token=? AND s.cursor=? AND s.page_count=? AND d.status!='deleted'
|
|
56
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')))`;
|
|
57
|
+
const args=[pkg.id,body.writerToken,state.cursor,state.page_count];
|
|
58
|
+
// INSERT + fragment + CAS + constraint are atomic. No cursor can advance
|
|
59
|
+
// without its exact persisted bytes, and a lost receipt replays last_result.
|
|
60
|
+
const token=crypto.randomUUID();
|
|
61
|
+
await env.DB.batch([
|
|
62
|
+
env.DB.prepare(`INSERT OR IGNORE INTO delivery_manifest_read_work(package_id,page_number,start_cursor,read_cursor)
|
|
63
|
+
SELECT ?,?,?,? WHERE ${fence}`).bind(pkg.id,state.page_count,state.cursor,state.cursor,...args),
|
|
64
|
+
...(rows.length?[env.DB.prepare(`INSERT INTO delivery_manifest_read_fragments(package_id,page_number,start_cursor,end_cursor,rows_json,digest)
|
|
65
|
+
SELECT ?,?,?,?,?,? WHERE ${fence} AND EXISTS(SELECT 1 FROM delivery_manifest_read_work WHERE package_id=? AND page_number=? AND read_cursor=? AND last_sequence=?)`)
|
|
66
|
+
.bind(pkg.id,state.page_count,work.read_cursor,end,json,digest,...args,pkg.id,state.page_count,work.read_cursor,work.last_sequence)]:[]),
|
|
67
|
+
env.DB.prepare(`UPDATE delivery_manifest_read_work SET read_cursor=?,entry_count=?,packed_bytes=?,wire_bytes=wire_bytes+?,
|
|
68
|
+
chain=?,prepared=?,last_sequence=?,last_result=? WHERE package_id=? AND page_number=? AND read_cursor=? AND last_sequence=? AND ${fence}`)
|
|
69
|
+
.bind(end,count,packed,rows.length?bytes(json):0,chain,+prepared,sequence,JSON.stringify(result),pkg.id,state.page_count,work.read_cursor,work.last_sequence,...args),
|
|
70
|
+
env.DB.prepare('INSERT INTO delivery_upload_budget_guards(token,ok) VALUES (?,CASE WHEN changes()=1 THEN 1 ELSE 0 END)').bind(token),
|
|
71
|
+
env.DB.prepare('DELETE FROM delivery_upload_budget_guards WHERE token=?').bind(token),
|
|
72
|
+
]);
|
|
73
|
+
return result;
|
|
74
|
+
}
|