@cardinali-studio/adminkit 2.2.48 → 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.
- package/dist/app/App.js +6 -6
- package/dist/app/app.css +67 -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 +299 -164
- 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/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 +108 -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/_shared/diagnostics.js +59 -0
- package/dist/functions/api/deliveries.js +61 -17
- package/dist/functions/api/delivery/multipart.js +156 -16
- 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
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|