@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,68 @@
|
|
|
1
|
+
import { b2ListPartsPage } from './b2.js';
|
|
2
|
+
import { assertManifestWriter, manifestVersion } from './delivery-manifest.js';
|
|
3
|
+
import { sha256 } from './delivery-crypto.js';
|
|
4
|
+
import { DELIVERY_MAX_ARCHIVE_BYTES, DELIVERY_PART_BYTES, validateDeliverySourceBytes } from './delivery-limits.js';
|
|
5
|
+
import { policyError } from './delivery-work-budget.js';
|
|
6
|
+
import { assertUploadSessionInvocation } from './delivery-upload-contract.js';
|
|
7
|
+
import { freeWork,needsPaid,assertFreePartRead } from './delivery-upload-free.js';
|
|
8
|
+
|
|
9
|
+
const invalid = message => policyError('delivery_parts_conflict', message);
|
|
10
|
+
// A preparation proof only: no receipt is deleted, created or weakened. This
|
|
11
|
+
// can run as separate requests on either profile; it does not certify Free CPU.
|
|
12
|
+
export async function verifyMultipartStep(env, body) {
|
|
13
|
+
const count = body.partCount, bytes = body.bytes;
|
|
14
|
+
if (!Number.isSafeInteger(count) || count < 1 || count > 10_000 || !Number.isSafeInteger(bytes) || bytes < 1 || bytes > DELIVERY_MAX_ARCHIVE_BYTES || Math.ceil(bytes / DELIVERY_PART_BYTES) !== count) throw invalid('Dimensione o conteggio multipart non valido');
|
|
15
|
+
if (!await env.DB.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='delivery_multipart_verification'").first()) throw policyError('upload_capability_changed', 'Migrazione della verifica multipart non disponibile', 503);
|
|
16
|
+
const upload = await env.DB.prepare(`SELECT u.*,p.manifest_json,p.source_bytes FROM delivery_uploads u
|
|
17
|
+
JOIN delivery_packages p ON p.id=u.package_id JOIN deliveries d ON d.id=u.delivery_id
|
|
18
|
+
WHERE u.id=? AND u.state='uploading' AND p.state='uploading' AND d.status!='deleted'
|
|
19
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))`).bind(String(body.uploadId || '')).first();
|
|
20
|
+
if (!upload || upload.variant !== 'originals' || manifestVersion(upload) !== 2) throw invalid('La verifica richiede originali v2 in caricamento');
|
|
21
|
+
assertUploadSessionInvocation(env, upload);
|
|
22
|
+
validateDeliverySourceBytes(upload.source_bytes);
|
|
23
|
+
await assertManifestWriter(env, upload.package_id, body.writerToken);
|
|
24
|
+
if(freeWork(env)) {
|
|
25
|
+
if(count>32)throw needsPaid();
|
|
26
|
+
await assertFreePartRead(env,upload.id);
|
|
27
|
+
}
|
|
28
|
+
const fence = `EXISTS(SELECT 1 FROM delivery_uploads u JOIN delivery_packages p ON p.id=u.package_id
|
|
29
|
+
JOIN deliveries d ON d.id=u.delivery_id JOIN delivery_manifest_state s ON s.package_id=p.id
|
|
30
|
+
WHERE u.id=? AND u.b2_upload_id=? AND u.object_key=? AND u.state='uploading' AND p.state='uploading'
|
|
31
|
+
AND s.writer_token=? AND d.status!='deleted'
|
|
32
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')))
|
|
33
|
+
AND (SELECT COUNT(*) FROM delivery_upload_parts WHERE upload_id=?)=?
|
|
34
|
+
AND (SELECT COALESCE(SUM(size),0) FROM delivery_upload_parts WHERE upload_id=?)=?`;
|
|
35
|
+
const args = [upload.id, upload.b2_upload_id, upload.object_key, body.writerToken, upload.id, count, upload.id, bytes];
|
|
36
|
+
const totals = await env.DB.prepare(`SELECT COUNT(*) n,MIN(part_number) lo,MAX(part_number) hi,COALESCE(SUM(size),0) bytes,
|
|
37
|
+
SUM(CASE WHEN digest IS NULL OR length(digest)!=64 OR digest GLOB '*[^a-f0-9]*' THEN 1 ELSE 0 END) pending
|
|
38
|
+
FROM delivery_upload_parts WHERE upload_id=?`).bind(upload.id).first();
|
|
39
|
+
if (totals.n !== count || totals.lo !== 1 || totals.hi !== count || totals.bytes !== bytes || totals.pending) throw invalid('Ricevute originali incomplete o non confermate');
|
|
40
|
+
const seed = await sha256(JSON.stringify(['multipart-verify-v1', upload.id, upload.b2_upload_id, upload.object_key, count, bytes]));
|
|
41
|
+
await env.DB.prepare(`INSERT OR IGNORE INTO delivery_multipart_verification(upload_id,remote_upload_id,object_key,expected_count,expected_bytes,chain)
|
|
42
|
+
SELECT ?,?,?,?,?,? WHERE ${fence}`).bind(upload.id, upload.b2_upload_id, upload.object_key, count, bytes, seed, ...args).run();
|
|
43
|
+
const job = await env.DB.prepare('SELECT * FROM delivery_multipart_verification WHERE upload_id=? AND remote_upload_id=?').bind(upload.id,upload.b2_upload_id).first();
|
|
44
|
+
if (!job || job.object_key !== upload.object_key || job.expected_count !== count || job.expected_bytes !== bytes) throw invalid('Generazione o dichiarazione multipart cambiata');
|
|
45
|
+
const reply = saved => ({ done: saved.state === 'verified', phase: 'parts', cursor: saved.cursor, total: count, bytes: saved.verified_bytes, proof: saved.chain });
|
|
46
|
+
if (job.state === 'verified') return reply(job);
|
|
47
|
+
let remote;
|
|
48
|
+
try { remote = await b2ListPartsPage(env, upload.object_key, upload.b2_upload_id, job.cursor); }
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (error.status === 404) throw policyError('upload_completion_recovery_required', 'Sessione remota non disponibile: verificare il completamento esistente con il percorso compatibile.');
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
if (!remote.parts.length) throw invalid('Pagina multipart remota vuota');
|
|
54
|
+
const saved = (await env.DB.prepare(`SELECT part_number,etag,size,digest FROM delivery_upload_parts WHERE upload_id=? AND part_number>? AND part_number<=? ORDER BY part_number LIMIT 32`).bind(upload.id, job.cursor, remote.parts.at(-1).partNumber).all()).results || [];
|
|
55
|
+
if (!remote.parts.length || remote.parts.length !== saved.length || remote.parts.some((p,i) => {
|
|
56
|
+
const s = saved[i]; return p.partNumber !== s.part_number || p.etag !== s.etag || p.size !== s.size || !/^[a-f0-9]{64}$/.test(s.digest) || p.size > DELIVERY_PART_BYTES || p.partNumber < count && p.size !== DELIVERY_PART_BYTES;
|
|
57
|
+
})) throw invalid('Le parti remote non corrispondono alle ricevute originali');
|
|
58
|
+
let chain = job.chain, verifiedBytes = job.verified_bytes;
|
|
59
|
+
for (const p of saved) { chain = await sha256(JSON.stringify([chain,p.part_number,p.etag,p.size,p.digest])); verifiedBytes += p.size; }
|
|
60
|
+
const cursor = saved.at(-1).part_number, done = cursor === count;
|
|
61
|
+
if (cursor > count || remote.truncated === done || done && verifiedBytes !== bytes) throw invalid('Confine finale multipart non valido');
|
|
62
|
+
const updated = await env.DB.prepare(`UPDATE delivery_multipart_verification SET cursor=?,verified_bytes=?,chain=?,state=?
|
|
63
|
+
WHERE upload_id=? AND remote_upload_id=? AND cursor=? AND chain=? AND ${fence}`)
|
|
64
|
+
.bind(cursor, verifiedBytes, chain, done ? 'verified' : 'scanning', upload.id, upload.b2_upload_id, job.cursor, job.chain, ...args).run();
|
|
65
|
+
await assertManifestWriter(env, upload.package_id, body.writerToken);
|
|
66
|
+
if (!updated.meta.changes) throw invalid('Verifica concorrente, annullata o generazione cambiata; rileggi il cursore');
|
|
67
|
+
return reply({ state: done ? 'verified' : 'scanning', cursor, verified_bytes: verifiedBytes, chain });
|
|
68
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// The legacy envelope is deliberately independent of the candidate Free/Paid
|
|
2
|
+
// micro-budgets. It accommodates the 1.8 MB v1 manifest and the 256 KiB v2
|
|
3
|
+
// entries array, with wrapper/escaping headroom. It is not a CPU certification.
|
|
4
|
+
export const DELIVERY_LEGACY_REQUEST_BYTES = 8 * 1024 * 1024;
|
|
5
|
+
export const DELIVERY_UPLOAD_REQUEST_BYTES = Object.freeze({free:40960,paid:278528});
|
|
6
|
+
|
|
7
|
+
// Reserved protocol entry point for a future rollout. Call only after the
|
|
8
|
+
// current namespace gate; the profile is server authority, never a header/body.
|
|
9
|
+
// Keep the legacy 8 MiB reader independent so old consumers remain compatible.
|
|
10
|
+
export function readUploadSessionJson(request,env) {
|
|
11
|
+
const max=DELIVERY_UPLOAD_REQUEST_BYTES[env.DELIVERY_UPLOAD_PROFILE];
|
|
12
|
+
if(!max)throw new DeliveryBodyError('Budget di upload non verificato',409,'upload_budget_unknown');
|
|
13
|
+
return readDeliveryJson(request,max);
|
|
14
|
+
}
|
|
15
|
+
export function readDeliveryUploadBody(request,env) {
|
|
16
|
+
return request.headers.has('X-Delivery-Upload-Protocol')?readUploadSessionJson(request,env):readDeliveryJson(request);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class DeliveryBodyError extends Error {
|
|
20
|
+
constructor(message, status, code) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.status = status;
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.retryable = false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Count the actual wire bytes, including whitespace and the whole JSON wrapper.
|
|
29
|
+
// Content-Length is only an early rejection; a small/missing value never grants
|
|
30
|
+
// permission to read an unbounded body. Do not clone/tee a request for parsing.
|
|
31
|
+
export async function readDeliveryJson(request, maxBytes = DELIVERY_LEGACY_REQUEST_BYTES) {
|
|
32
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > DELIVERY_LEGACY_REQUEST_BYTES) {
|
|
33
|
+
throw new TypeError('Invalid server request budget');
|
|
34
|
+
}
|
|
35
|
+
const exceeded = () => new DeliveryBodyError('Il corpo della richiesta supera il budget di upload', 413, 'upload_budget_exceeded');
|
|
36
|
+
const declared = request.headers.get('content-length');
|
|
37
|
+
if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
|
|
38
|
+
void request.body?.cancel().catch(() => {});
|
|
39
|
+
throw exceeded();
|
|
40
|
+
}
|
|
41
|
+
if (!request.body) throw new DeliveryBodyError('Corpo JSON non valido', 400);
|
|
42
|
+
const reader = request.body.getReader();
|
|
43
|
+
let bytes = 0;
|
|
44
|
+
const decoder = new TextDecoder(), chunks = [];
|
|
45
|
+
try {
|
|
46
|
+
for (;;) {
|
|
47
|
+
const { value, done } = await reader.read();
|
|
48
|
+
if (done) break;
|
|
49
|
+
bytes += value.byteLength;
|
|
50
|
+
if (bytes > maxBytes) {
|
|
51
|
+
// Do not wait for a potentially stalled upstream producer to cancel.
|
|
52
|
+
void reader.cancel().catch(() => {});
|
|
53
|
+
throw exceeded();
|
|
54
|
+
}
|
|
55
|
+
chunks.push(decoder.decode(value, { stream: true }));
|
|
56
|
+
}
|
|
57
|
+
chunks.push(decoder.decode());
|
|
58
|
+
return JSON.parse(chunks.join(''));
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error instanceof DeliveryBodyError) throw error;
|
|
61
|
+
throw new DeliveryBodyError('Corpo JSON non valido', 400);
|
|
62
|
+
} finally {
|
|
63
|
+
reader.releaseLock();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function deliveryBodyErrorResponse(error) {
|
|
68
|
+
if (!(error instanceof DeliveryBodyError)) throw error;
|
|
69
|
+
return new Response(JSON.stringify({ ok: false, error: error.message,
|
|
70
|
+
...(error.code ? { code: error.code, retryable: false } : {}) }), {
|
|
71
|
+
status: error.status,
|
|
72
|
+
headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
|
|
73
|
+
});
|
|
74
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Server-signed requests already have a fresh signature. A denied HEAD may
|
|
2
|
+
// still be answered by the existing one-byte GET fallback.
|
|
3
|
+
export function storageControlRequest(signedRequest) {
|
|
4
|
+
return async (env, method, key, options) => {
|
|
5
|
+
const response = await signedRequest(env, method, key, options);
|
|
6
|
+
if (response.status === 401 || (response.status === 403 && method !== "HEAD")) {
|
|
7
|
+
await response.body?.cancel();
|
|
8
|
+
throw Object.assign(new Error("Il servizio non può accedere ai file. Avvisa chi gestisce il sito, poi riprendi il caricamento."), {
|
|
9
|
+
code: "upload_storage_access_denied", status: 502, retryable: false, providerStatus: response.status,
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
return response;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { sha256 } from './delivery-crypto.js';
|
|
2
|
+
|
|
3
|
+
// Internal ledger only. No env flag, HTTP action or discovery can turn it on.
|
|
4
|
+
export const UPLOAD_ADMISSION_ROLLOUT_ENABLED = false;
|
|
5
|
+
export const UPLOAD_BUDGET_RESOURCES = Object.freeze(['requests', 'reads', 'writes', 'storageBytes', 'b2Operations', 'cpuMs']);
|
|
6
|
+
const resources = UPLOAD_BUDGET_RESOURCES;
|
|
7
|
+
const id = value => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,159}$/.test(value);
|
|
8
|
+
const number = value => Number.isSafeInteger(value) && value >= 0;
|
|
9
|
+
const fail = (code, status = 409) => Object.assign(new Error({
|
|
10
|
+
upload_budget_unknown: 'Budget di upload non verificato o non aggiornato',
|
|
11
|
+
upload_quota_exhausted: 'Budget di upload esaurito: la sessione è conservata',
|
|
12
|
+
upload_capability_changed: 'Contratto di upload cambiato: rileggi la stessa sessione',
|
|
13
|
+
upload_budget_exceeded: 'Il lavoro supera la prenotazione della sessione',
|
|
14
|
+
upload_profile_required: 'Profilo di esecuzione non disponibile',
|
|
15
|
+
}[code]), { code, status, retryable: false });
|
|
16
|
+
function vector(value) {
|
|
17
|
+
if (!value || typeof value !== 'object' || Object.keys(value).some(k => !resources.includes(k)) ||
|
|
18
|
+
resources.some(k => !number(value[k]))) throw fail('upload_budget_unknown');
|
|
19
|
+
return Object.fromEntries(resources.map(k => [k, value[k]]));
|
|
20
|
+
}
|
|
21
|
+
const period = (resource, now) => resource === 'storageBytes' ? 'retained' : new Date(now).toISOString().slice(0, 10);
|
|
22
|
+
function clock(now) { if (!Number.isSafeInteger(now) || now < 0) throw fail('upload_budget_unknown'); }
|
|
23
|
+
|
|
24
|
+
// The caller is a trusted, offline/installation accounting process, not an
|
|
25
|
+
// upload client. Values ALREADY include the reserve for other workloads, lag,
|
|
26
|
+
// cleanup and the candidate 20% margin. No billing API is called by the ledger.
|
|
27
|
+
// A watermark read from THIS DB is mandatory: concurrent consumption aborts the
|
|
28
|
+
// entire snapshot rather than attributing an account sample to the wrong state.
|
|
29
|
+
export async function installUploadBudgetSnapshot(env, snapshot, expected, now = Date.now()) {
|
|
30
|
+
clock(now);
|
|
31
|
+
if (!snapshot || !id(snapshot.revision) || !number(snapshot.expiresAt) || snapshot.expiresAt <= now ||
|
|
32
|
+
snapshot.expiresAt - now > 300_000 || snapshot.observedAt > now || now - snapshot.observedAt > 60_000 ||
|
|
33
|
+
!number(snapshot.observedAt) || !expected || typeof expected !== 'object') throw fail('upload_budget_unknown');
|
|
34
|
+
const assigned = vector(snapshot.transferLimit), account = vector(snapshot.accountRemaining);
|
|
35
|
+
const token = crypto.randomUUID(), statements = [];
|
|
36
|
+
for (const resource of resources) {
|
|
37
|
+
const old = expected[resource];
|
|
38
|
+
if (old !== null && (!old || !number(old.used) || !id(old.revision) || typeof old.period !== 'string')) throw fail('upload_budget_unknown');
|
|
39
|
+
const currentPeriod = period(resource, now);
|
|
40
|
+
if (old && (resource === 'storageBytes' ? old.period !== 'retained' : !/^\d{4}-\d{2}-\d{2}$/.test(old.period) || old.period > currentPeriod)) {
|
|
41
|
+
throw fail('upload_budget_unknown');
|
|
42
|
+
}
|
|
43
|
+
const used = old?.period === currentPeriod ? old.used : 0;
|
|
44
|
+
if (old === null) {
|
|
45
|
+
statements.push(env.DB.prepare(`INSERT INTO delivery_upload_budgets
|
|
46
|
+
(resource,period,revision,transfer_limit,account_remaining,observed_used,used,reserved,observed_at,expires_at)
|
|
47
|
+
VALUES (?,?,?,?,?,?,?,0,?,?) ON CONFLICT(resource) DO NOTHING`)
|
|
48
|
+
.bind(resource,currentPeriod,snapshot.revision,assigned[resource],account[resource],used,used,snapshot.observedAt,snapshot.expiresAt));
|
|
49
|
+
} else {
|
|
50
|
+
// Midnight resets the daily used counter, NEVER the residual debt.
|
|
51
|
+
statements.push(env.DB.prepare(`UPDATE delivery_upload_budgets SET period=?,revision=?,
|
|
52
|
+
transfer_limit=?,account_remaining=?,observed_used=?,used=?,observed_at=?,expires_at=?
|
|
53
|
+
WHERE resource=? AND period=? AND used=? AND revision=? AND observed_at<=?`)
|
|
54
|
+
.bind(currentPeriod,snapshot.revision,assigned[resource],account[resource],used,used,snapshot.observedAt,snapshot.expiresAt,
|
|
55
|
+
resource,old.period,old.used,old.revision,snapshot.observedAt));
|
|
56
|
+
}
|
|
57
|
+
statements.push(env.DB.prepare('INSERT INTO delivery_upload_budget_guards(token,ok) VALUES (?,CASE WHEN changes()=1 THEN 1 ELSE 0 END)').bind(token));
|
|
58
|
+
statements.push(env.DB.prepare('DELETE FROM delivery_upload_budget_guards WHERE token=?').bind(token));
|
|
59
|
+
}
|
|
60
|
+
try { await env.DB.batch(statements); }
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (/CHECK constraint failed/.test(String(error?.message))) throw fail('upload_budget_unknown');
|
|
63
|
+
throw error; // DB unavailable does not mean quota zero or permission to retry a new session.
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function readUploadBudgetWatermark(env) {
|
|
68
|
+
const { results } = await env.DB.prepare('SELECT resource,period,used,revision FROM delivery_upload_budgets').all();
|
|
69
|
+
return Object.fromEntries(resources.map(resource => [resource, results.find(r => r.resource === resource) || null]));
|
|
70
|
+
}
|
|
71
|
+
async function knownBudgets(env, now) {
|
|
72
|
+
const { results } = await env.DB.prepare('SELECT * FROM delivery_upload_budgets').all();
|
|
73
|
+
if (results.length !== resources.length || resources.some(r => !results.some(b => b.resource === r && b.period === period(r, now) && b.expires_at > now))) {
|
|
74
|
+
throw fail('upload_budget_unknown');
|
|
75
|
+
}
|
|
76
|
+
return results;
|
|
77
|
+
}
|
|
78
|
+
export async function assertUploadBudgetFresh(env, now = Date.now(), revision) {
|
|
79
|
+
const budgets = await knownBudgets(env, now);
|
|
80
|
+
if (revision!==undefined && budgets.some(b=>b.revision!==revision)) throw fail('upload_budget_unknown');
|
|
81
|
+
if (budgets.some(b => b.used+b.reserved>b.transfer_limit || b.reserved>b.account_remaining-(b.used-b.observed_used))) {
|
|
82
|
+
throw fail('upload_quota_exhausted', 429);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function contractValue(contract) {
|
|
86
|
+
if (!contract || contract.pipelineContractVersion !== 1 || !/^[a-f0-9]{64}$/.test(contract.capabilityRevision || '') ||
|
|
87
|
+
!id(contract.budgetRevision) || !['free','paid'].includes(contract.profile) ||
|
|
88
|
+
typeof contract.envelopeId !== 'string' || !id(contract.envelopeId) ||
|
|
89
|
+
!contract.effectiveLimits || typeof contract.effectiveLimits !== 'object' || Array.isArray(contract.effectiveLimits)) {
|
|
90
|
+
throw fail('upload_capability_changed');
|
|
91
|
+
}
|
|
92
|
+
// This is a server-owned immutable document; clients cannot submit it to any
|
|
93
|
+
// route. Hash the exact stored contract; no writer token/generation rotation.
|
|
94
|
+
const text = JSON.stringify(contract);
|
|
95
|
+
if (new TextEncoder().encode(text).byteLength > 16 * 1024) throw fail('upload_budget_exceeded', 413);
|
|
96
|
+
return text;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function reserveUploadBudget(env, sessionId, cost, contract, now = Date.now(), commit) {
|
|
100
|
+
clock(now);
|
|
101
|
+
if (!id(sessionId)) throw fail('upload_capability_changed');
|
|
102
|
+
const amounts = vector(cost), encoded = JSON.stringify(amounts), contractJson = contractValue(contract);
|
|
103
|
+
if (resources.some(r => amounts[r] < 1)) throw fail('upload_budget_unknown');
|
|
104
|
+
const planHash = await sha256(contractJson + '\n' + encoded);
|
|
105
|
+
const previous = await env.DB.prepare('SELECT * FROM delivery_upload_admissions WHERE session_id=?').bind(sessionId).first();
|
|
106
|
+
if (previous) {
|
|
107
|
+
if (previous.plan_hash !== planHash) throw fail('upload_capability_changed');
|
|
108
|
+
// Replay conserves the reservation even if the account observation expired.
|
|
109
|
+
// It does not grant a lease or permit more work under an unknown budget.
|
|
110
|
+
return { replay: true, state: previous.state, remaining: JSON.parse(previous.remaining_json) };
|
|
111
|
+
}
|
|
112
|
+
if (!['free','paid'].includes(env.DELIVERY_UPLOAD_PROFILE) || contract.profile !== env.DELIVERY_UPLOAD_PROFILE) {
|
|
113
|
+
throw fail('upload_profile_required');
|
|
114
|
+
}
|
|
115
|
+
await knownBudgets(env, now);
|
|
116
|
+
const token = crypto.randomUUID();
|
|
117
|
+
const conditions = resources.map(() => `EXISTS (SELECT 1 FROM delivery_upload_budgets WHERE resource=? AND period=? AND revision=?
|
|
118
|
+
AND expires_at>? AND ?>=0 AND transfer_limit-used-reserved>=? AND account_remaining-(used-observed_used)-reserved>=?)`).join(' AND ');
|
|
119
|
+
const bindings = resources.flatMap(r => [r,period(r,now),contract.budgetRevision,now,amounts[r],amounts[r],amounts[r]]);
|
|
120
|
+
const statements = [env.DB.prepare(`INSERT INTO delivery_upload_admissions
|
|
121
|
+
(session_id,plan_hash,contract_json,remaining_json,decision_token,created_at)
|
|
122
|
+
SELECT ?,?,?,?,?,? WHERE ${conditions} ON CONFLICT(session_id) DO NOTHING`)
|
|
123
|
+
.bind(sessionId,planHash,contractJson,encoded,token,now,...bindings)];
|
|
124
|
+
for (const r of resources) statements.push(env.DB.prepare(`UPDATE delivery_upload_budgets SET reserved=reserved+?
|
|
125
|
+
WHERE resource=? AND EXISTS (SELECT 1 FROM delivery_upload_admissions WHERE session_id=? AND decision_token=?)`)
|
|
126
|
+
.bind(amounts[r],r,sessionId,token));
|
|
127
|
+
// Trusted composition only: package + contract can be inserted atomically
|
|
128
|
+
// with the reservation. No callback or SQL is ever taken from an HTTP body.
|
|
129
|
+
if (commit) {
|
|
130
|
+
const extra = commit({ token, guard: 'EXISTS (SELECT 1 FROM delivery_upload_admissions WHERE session_id=? AND decision_token=?)', args: [sessionId,token] });
|
|
131
|
+
if (!Array.isArray(extra)) throw fail('upload_budget_unknown');
|
|
132
|
+
statements.push(...extra);
|
|
133
|
+
}
|
|
134
|
+
await env.DB.batch(statements);
|
|
135
|
+
const saved = await env.DB.prepare('SELECT * FROM delivery_upload_admissions WHERE session_id=?').bind(sessionId).first();
|
|
136
|
+
if (!saved) {
|
|
137
|
+
const current = await knownBudgets(env, now);
|
|
138
|
+
if (current.some(r => r.revision !== contract.budgetRevision)) throw fail('upload_budget_unknown');
|
|
139
|
+
throw fail('upload_quota_exhausted', 429);
|
|
140
|
+
}
|
|
141
|
+
if (saved.plan_hash !== planHash) throw fail('upload_capability_changed');
|
|
142
|
+
return { replay: saved.decision_token !== token, state: saved.state, remaining: JSON.parse(saved.remaining_json) };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Convert a part of debt into observed application consumption once, in the
|
|
146
|
+
// same transaction. Retry with the SAME event id after an uncertain response.
|
|
147
|
+
// The caller includes ledger, adapter, recovery and cleanup costs in the vector.
|
|
148
|
+
export async function consumeUploadBudget(env, sessionId, eventId, cost, now = Date.now()) {
|
|
149
|
+
clock(now);
|
|
150
|
+
if (!id(sessionId) || !id(eventId)) throw fail('upload_capability_changed');
|
|
151
|
+
const amounts = vector(cost), encoded = JSON.stringify(amounts), deltaHash = await sha256(encoded);
|
|
152
|
+
const old = await env.DB.prepare('SELECT * FROM delivery_upload_budget_events WHERE event_id=?').bind(eventId).first();
|
|
153
|
+
if (old) {
|
|
154
|
+
if (old.session_id !== sessionId || old.delta_hash !== deltaHash) throw fail('upload_capability_changed');
|
|
155
|
+
return { replay: true };
|
|
156
|
+
}
|
|
157
|
+
await knownBudgets(env, now);
|
|
158
|
+
const token = crypto.randomUUID(), enough = resources.map(r => `json_extract(remaining_json,'$.${r}')>=?`).join(' AND ');
|
|
159
|
+
const valid = resources.map(() => `EXISTS (SELECT 1 FROM delivery_upload_budgets WHERE resource=? AND period=? AND expires_at>?)`).join(' AND ');
|
|
160
|
+
const statements = [env.DB.prepare(`INSERT INTO delivery_upload_budget_events(event_id,session_id,delta_hash,decision_token,created_at)
|
|
161
|
+
SELECT ?,?,?,?,? WHERE EXISTS (SELECT 1 FROM delivery_upload_admissions WHERE session_id=? AND state='reserved' AND ${enough}) AND ${valid}
|
|
162
|
+
ON CONFLICT(event_id) DO NOTHING`).bind(eventId,sessionId,deltaHash,token,now,sessionId,...resources.map(r=>amounts[r]),
|
|
163
|
+
...resources.flatMap(r=>[r,period(r,now),now]))];
|
|
164
|
+
const event = 'EXISTS (SELECT 1 FROM delivery_upload_budget_events WHERE event_id=? AND decision_token=?)';
|
|
165
|
+
for (const r of resources) statements.push(env.DB.prepare(`UPDATE delivery_upload_budgets SET used=used+?,reserved=reserved-?
|
|
166
|
+
WHERE resource=? AND ${event}`).bind(amounts[r],amounts[r],r,eventId,token));
|
|
167
|
+
const fields = resources.map(r => `'$.${r}',json_extract(remaining_json,'$.${r}')-?`).join(',');
|
|
168
|
+
statements.push(env.DB.prepare(`UPDATE delivery_upload_admissions SET remaining_json=json_set(remaining_json,${fields})
|
|
169
|
+
WHERE session_id=? AND ${event}`).bind(...resources.map(r=>amounts[r]),sessionId,eventId,token));
|
|
170
|
+
await env.DB.batch(statements);
|
|
171
|
+
const saved = await env.DB.prepare('SELECT * FROM delivery_upload_budget_events WHERE event_id=?').bind(eventId).first();
|
|
172
|
+
if (!saved) throw fail('upload_budget_exceeded', 413);
|
|
173
|
+
if (saved.session_id !== sessionId || saved.delta_hash !== deltaHash) throw fail('upload_capability_changed');
|
|
174
|
+
return { replay: saved.decision_token !== token };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// A slot is not quota. A pause/expired lease never releases accounting debt.
|
|
178
|
+
// The owner must already have passed the manifest writer fencing at its caller.
|
|
179
|
+
export async function acquireUploadSlot(env, sessionId, owner, now = Date.now(), { includeRunningUnits = false } = {}) {
|
|
180
|
+
clock(now);
|
|
181
|
+
const slots = env.DELIVERY_UPLOAD_PROFILE === 'free' ? 1 : env.DELIVERY_UPLOAD_PROFILE === 'paid' ? 2 : 0;
|
|
182
|
+
if (!slots) throw fail('upload_profile_required');
|
|
183
|
+
if (!id(owner) || !id(sessionId)) throw fail('upload_capability_changed');
|
|
184
|
+
await knownBudgets(env, now);
|
|
185
|
+
const token = crypto.randomUUID();
|
|
186
|
+
const changed = await env.DB.prepare(`UPDATE delivery_upload_admissions SET lease_owner=?,lease_token=?,lease_until=?
|
|
187
|
+
WHERE session_id=? AND state='reserved' AND (lease_until<=? OR lease_owner=?)
|
|
188
|
+
AND (SELECT COUNT(*) FROM delivery_upload_admissions WHERE state='reserved'
|
|
189
|
+
AND (lease_until>? ${includeRunningUnits ? "OR EXISTS(SELECT 1 FROM delivery_upload_units u WHERE u.session_id=delivery_upload_admissions.session_id AND u.state='running')" : ''}) AND session_id!=?)<?
|
|
190
|
+
AND NOT EXISTS (SELECT 1 FROM delivery_upload_budgets WHERE expires_at<=? OR used+reserved>transfer_limit
|
|
191
|
+
OR reserved>account_remaining-(used-observed_used))`)
|
|
192
|
+
.bind(owner,token,now+60_000,sessionId,now,owner,now,sessionId,slots,now).run();
|
|
193
|
+
if (!changed.meta?.changes) throw fail('upload_quota_exhausted', 429);
|
|
194
|
+
return { token, expiresAt: now+60_000 };
|
|
195
|
+
}
|
|
196
|
+
export async function releaseUploadSlot(env, sessionId, owner, token) {
|
|
197
|
+
if (!id(sessionId) || !id(owner) || !id(token)) throw fail('upload_capability_changed');
|
|
198
|
+
const changed = await env.DB.prepare(`UPDATE delivery_upload_admissions SET lease_until=0
|
|
199
|
+
WHERE session_id=? AND lease_owner=? AND lease_token=?`).bind(sessionId,owner,token).run();
|
|
200
|
+
return !!changed.meta?.changes;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// INTERNAL terminal cleanup only: the caller must prove that no remote work is
|
|
204
|
+
// in flight and cleanup/retention liability is accounted. Pausing is NOT close.
|
|
205
|
+
// Consumed storage remains used until a separately reconciled installation
|
|
206
|
+
// snapshot; closing never pretends that an object has disappeared from B2.
|
|
207
|
+
export async function closeUploadBudgetAfterCleanup(env, sessionId, now = Date.now()) {
|
|
208
|
+
clock(now);
|
|
209
|
+
if (!id(sessionId)) throw fail('upload_capability_changed');
|
|
210
|
+
const token = crypto.randomUUID();
|
|
211
|
+
const condition = `EXISTS (SELECT 1 FROM delivery_upload_admissions WHERE session_id=? AND state='closed' AND decision_token=?)`;
|
|
212
|
+
const statements = [env.DB.prepare(`UPDATE delivery_upload_admissions SET state='closed',decision_token=?
|
|
213
|
+
WHERE session_id=? AND state='reserved' AND lease_until<=?`).bind(token,sessionId,now)];
|
|
214
|
+
for (const r of resources) statements.push(env.DB.prepare(`UPDATE delivery_upload_budgets SET reserved=reserved-
|
|
215
|
+
(SELECT json_extract(remaining_json,'$.${r}') FROM delivery_upload_admissions WHERE session_id=?)
|
|
216
|
+
WHERE resource=? AND ${condition}`).bind(sessionId,r,sessionId,token));
|
|
217
|
+
statements.push(env.DB.prepare(`UPDATE delivery_upload_admissions SET remaining_json=? WHERE session_id=? AND decision_token=?`)
|
|
218
|
+
.bind(JSON.stringify(Object.fromEntries(resources.map(r=>[r,0]))),sessionId,token));
|
|
219
|
+
const results = await env.DB.batch(statements);
|
|
220
|
+
return !!results[0].meta?.changes;
|
|
221
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Shared server invariants. A request body/env string cannot manufacture a
|
|
2
|
+
// permit: only the session coordinator grants one to its invocation-local env.
|
|
3
|
+
const permits = new WeakMap();
|
|
4
|
+
export const uploadSessionError = (code, message, status = 409) => Object.assign(new Error(message), { code, status, retryable: false });
|
|
5
|
+
export const opaqueUploadId = v => typeof v === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,159}$/.test(v);
|
|
6
|
+
export function uploadSessionMarker(pkg) {
|
|
7
|
+
let manifest;
|
|
8
|
+
try { manifest = JSON.parse(pkg?.manifest_json || '{}'); } catch { return null; }
|
|
9
|
+
if (!Object.hasOwn(manifest, 'uploadSession')) return null;
|
|
10
|
+
const marker = manifest.uploadSession;
|
|
11
|
+
if (!marker || marker.version !== 1 || !opaqueUploadId(marker.id) || !/^[a-f0-9]{64}$/.test(marker.contractHash || '') ||
|
|
12
|
+
marker.id !== (pkg.package_id || pkg.id) || manifest.version !== 2 || manifest.generation !== marker.id) {
|
|
13
|
+
throw uploadSessionError('upload_capability_changed', 'Contratto della sessione non riconosciuto');
|
|
14
|
+
}
|
|
15
|
+
return marker;
|
|
16
|
+
}
|
|
17
|
+
export function assertUploadSessionInvocation(env, pkg) {
|
|
18
|
+
const marker = uploadSessionMarker(pkg);
|
|
19
|
+
const permit = permits.get(env);
|
|
20
|
+
if (marker && (!permit?.active || permit.id !== marker.id)) {
|
|
21
|
+
throw uploadSessionError('upload_capability_changed', 'La sessione richiede il coordinatore di upload; nessun fallback legacy');
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export function uploadSessionSequence(env) { const p=permits.get(env);return p?.active?p.sequence:undefined; }
|
|
25
|
+
export async function withUploadSessionInvocation(env, sessionId, work, sequence) {
|
|
26
|
+
const local = { ...env };
|
|
27
|
+
const permit = { id: sessionId, active: true, sequence };
|
|
28
|
+
permits.set(local, permit);
|
|
29
|
+
try { return await work(local); } finally { permit.active = false; permits.delete(local); }
|
|
30
|
+
}
|
|
31
|
+
export function inheritUploadSessionInvocation(from, scoped) {
|
|
32
|
+
const permit = permits.get(from);
|
|
33
|
+
if (permit?.active) permits.set(scoped, permit);
|
|
34
|
+
return scoped;
|
|
35
|
+
}
|
|
36
|
+
// Object key order is not part of a receipt. Array order, values and UTF-8 are.
|
|
37
|
+
export function canonicalUploadJson(value) {
|
|
38
|
+
if (value === null || typeof value !== 'object') {
|
|
39
|
+
if (typeof value === 'number' && !Number.isFinite(value) || value === undefined) throw uploadSessionError('upload_capability_changed', 'Contenuto operazione non valido');
|
|
40
|
+
return JSON.stringify(value);
|
|
41
|
+
}
|
|
42
|
+
if (Array.isArray(value)) return '[' + value.map(canonicalUploadJson).join(',') + ']';
|
|
43
|
+
return '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + canonicalUploadJson(value[key])).join(',') + '}';
|
|
44
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { uploadSessionError, inheritUploadSessionInvocation } from './delivery-upload-contract.js';
|
|
2
|
+
import { DELIVERY_WORK_BUDGET } from './delivery-work-budget.js';
|
|
3
|
+
|
|
4
|
+
// Internal, invocation-local authority. Neither an HTTP field nor an env string
|
|
5
|
+
// can opt a legacy request into these restrictions.
|
|
6
|
+
export const FREE_UPLOAD_WORK = Symbol('Free upload work');
|
|
7
|
+
export const FREE_UPLOAD_UNIT = Object.freeze({ entries:32, metadataBytes:32768,
|
|
8
|
+
dataBytes:12288, responseBytes:32768, d1Calls:32, externalCalls:16 });
|
|
9
|
+
const size = value => new TextEncoder().encode(JSON.stringify(value ?? null)).length;
|
|
10
|
+
export const needsPaid = () => uploadSessionError('upload_profile_required',
|
|
11
|
+
'Questa unità indivisibile supera il budget Free; riprendi la stessa sessione con un profilo qualificato.');
|
|
12
|
+
export const freeWork = env => env[FREE_UPLOAD_WORK];
|
|
13
|
+
|
|
14
|
+
// The coordinator/control plane has its own accounting/certification envelope.
|
|
15
|
+
// This is an additional hard ceiling on the dispatched helper, not a claim that
|
|
16
|
+
// its counters measure CPU, D1 billed rows, or the whole authenticated request.
|
|
17
|
+
export function createFreeUploadWork(env) {
|
|
18
|
+
const used={metadataBytes:0,d1Calls:0,externalCalls:0,statements:0,units:0};
|
|
19
|
+
const charge=(key,n)=>{if(!Number.isSafeInteger(n)||n<0||used[key]+n>FREE_UPLOAD_UNIT[key])throw needsPaid();used[key]+=n;};
|
|
20
|
+
const read=value=>{charge('metadataBytes',size(value));return value;};
|
|
21
|
+
const raw=Symbol('statement');
|
|
22
|
+
const wrap=statement=>({[raw]:statement,bind(...args){return wrap(statement.bind(...args));},
|
|
23
|
+
async first(...args){charge('d1Calls',1);used.statements++;return read(await statement.first(...args));},
|
|
24
|
+
async all(...args){charge('d1Calls',1);used.statements++;const result=await statement.all(...args);read(result.results||[]);return result;},
|
|
25
|
+
async run(){charge('d1Calls',1);used.statements++;return statement.run();}});
|
|
26
|
+
const budget={used,canRead:n=>Number.isSafeInteger(n)&&n>=0&&n+4096<=FREE_UPLOAD_UNIT.metadataBytes-used.metadataBytes,
|
|
27
|
+
external(){charge('externalCalls',1);},readBytes(n){charge('metadataBytes',n);}};
|
|
28
|
+
const scoped=Object.create(env);
|
|
29
|
+
Object.defineProperties(scoped,{DB:{value:{prepare(sql){return wrap(env.DB.prepare(sql));},
|
|
30
|
+
async batch(statements){charge('d1Calls',1);used.statements+=statements.length;return env.DB.batch(statements.map(s=>s[raw]));}}},
|
|
31
|
+
[FREE_UPLOAD_WORK]:{value:budget},[DELIVERY_WORK_BUDGET]:{value:budget}});
|
|
32
|
+
return {env:inheritUploadSessionInvocation(env,scoped),budget};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// JSON escaping can make D1's entry_json string much larger than the stored
|
|
36
|
+
// UTF-8 entry. Always size the actual application row shape in SQL, before read.
|
|
37
|
+
export async function assertFreeEntryRead(env,packageId,where,args=[],copies=1) {
|
|
38
|
+
if(!freeWork(env))return;
|
|
39
|
+
const bound=await env.DB.prepare(`SELECT COUNT(*) n,COALESCE(SUM(length(CAST(
|
|
40
|
+
json_object('entry_id',entry_id,'entry_json',entry_json,'claimed',1) AS BLOB))+1),0)+2 bytes
|
|
41
|
+
FROM (SELECT entry_id,entry_json FROM delivery_manifest_entries WHERE package_id=? ${where} LIMIT 33)`)
|
|
42
|
+
.bind(packageId,...args).first();
|
|
43
|
+
if(bound.n>32||bound.bytes*copies>FREE_UPLOAD_UNIT.dataBytes||!freeWork(env).canRead(bound.bytes*copies))throw needsPaid();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function assertFreePartRead(env,uploadId) {
|
|
47
|
+
if(!freeWork(env))return;
|
|
48
|
+
const bound=await env.DB.prepare(`SELECT COUNT(*) n,COALESCE(SUM(length(CAST(json_object(
|
|
49
|
+
'part_number',part_number,'etag',etag,'size',size,'digest',digest) AS BLOB))+1),0)+2 bytes
|
|
50
|
+
FROM (SELECT part_number,etag,size,digest FROM delivery_upload_parts WHERE upload_id=? ORDER BY part_number LIMIT 33)`)
|
|
51
|
+
.bind(uploadId).first();
|
|
52
|
+
// Reconcile reads the receipts twice to close the concurrent-record race.
|
|
53
|
+
if(bound.n>32||bound.bytes*2>FREE_UPLOAD_UNIT.dataBytes||!freeWork(env).canRead(bound.bytes*2))throw needsPaid();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function assertFreeCheckpointRead(env,packageId) {
|
|
57
|
+
if(!freeWork(env))return;
|
|
58
|
+
const bound=await env.DB.prepare(`SELECT length(CAST(checkpoint_json AS BLOB)) bytes,
|
|
59
|
+
json_extract(checkpoint_json,'$.validation.partCount') parts,
|
|
60
|
+
json_extract(checkpoint_json,'$.offset') offset FROM delivery_checkpoints WHERE package_id=?`).bind(packageId).first();
|
|
61
|
+
if(bound&&(bound.bytes*2>FREE_UPLOAD_UNIT.dataBytes||!freeWork(env).canRead(bound.bytes*2)||
|
|
62
|
+
(bound.parts??Math.floor(bound.offset/16777216))>32))throw needsPaid();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function readFreeManifestDraft(env,body) {
|
|
66
|
+
const after=body.after??-1;
|
|
67
|
+
if(!Number.isSafeInteger(after)||after< -1)throw uploadSessionError('delivery_manifest','Pagina non valida',400);
|
|
68
|
+
// IDs/lengths only for the lookahead; never decode an entry to discard it.
|
|
69
|
+
const sizes=(await env.DB.prepare(`SELECT entry_id,length(CAST(json_object('entry_id',entry_id,
|
|
70
|
+
'entry_json',entry_json) AS BLOB))+1 bytes FROM delivery_manifest_entries
|
|
71
|
+
WHERE package_id=? AND entry_id>? ORDER BY entry_id LIMIT 33`).bind(body.packageId,after).all()).results||[];
|
|
72
|
+
let n=0,bytes=2;
|
|
73
|
+
for(const row of sizes){if(n===32||bytes+row.bytes>FREE_UPLOAD_UNIT.dataBytes)break;n++;bytes+=row.bytes;}
|
|
74
|
+
if(!n&&sizes.length)throw needsPaid();
|
|
75
|
+
if(freeWork(env)&&!freeWork(env).canRead(bytes))throw needsPaid();
|
|
76
|
+
const rows=(await env.DB.prepare(`SELECT entry_id,entry_json FROM delivery_manifest_entries
|
|
77
|
+
WHERE package_id=? AND entry_id>? ORDER BY entry_id LIMIT ?`).bind(body.packageId,after,n).all()).results||[];
|
|
78
|
+
return {entries:rows.map(r=>({index:r.entry_id,entry:JSON.parse(r.entry_json)})),
|
|
79
|
+
nextCursor:sizes.length>n?rows.at(-1).entry_id:null};
|
|
80
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { sha256 } from './delivery-crypto.js';
|
|
2
|
+
import { v2Enabled } from './delivery-manifest.js';
|
|
3
|
+
|
|
4
|
+
// No feature can be enabled by an environment flag until its implementation and
|
|
5
|
+
// consumer certification land. Bump this revision when policy semantics change.
|
|
6
|
+
const POLICY_REVISION = 'upload-pipeline-1-disabled-3';
|
|
7
|
+
export const COMMON_FINALIZATION_ROLLOUT_ENABLED = false;
|
|
8
|
+
export const PAID_UPLOAD_ROLLOUT_ENABLED = false;
|
|
9
|
+
const FEATURES = Object.freeze({
|
|
10
|
+
presignBatch: false,
|
|
11
|
+
recordBatch: false,
|
|
12
|
+
asyncCheckpoint: false,
|
|
13
|
+
segmentedFinalize: false,
|
|
14
|
+
coalescedFinalize: false,
|
|
15
|
+
minimalActivate: false,
|
|
16
|
+
durableExecutor: false,
|
|
17
|
+
});
|
|
18
|
+
const RESERVED_ACTIONS = new Set([...Object.keys(FEATURES), 'manifestReplayBatch', 'asyncCheckpointStatus', 'multipartVerifyStep', 'completePaid',
|
|
19
|
+
'uploadSessionCreate', 'uploadSessionStatus', 'uploadSessionUnit', 'uploadSessionPause', 'uploadSessionRecover']);
|
|
20
|
+
const REQUEST_MARKERS = ['uploadPipeline', 'pipelineContractVersion', 'capabilityRevision', 'pipelineFeature', 'uploadSession', 'sessionId'];
|
|
21
|
+
|
|
22
|
+
export async function deliveryCapabilities(env) {
|
|
23
|
+
const legacy = {
|
|
24
|
+
manifestVersion: v2Enabled(env) ? 2 : 1,
|
|
25
|
+
jpegEnabled: env.DELIVERY_JPEG_ENABLED === 'true',
|
|
26
|
+
downloadLabelsEnabled: env.DELIVERY_DOWNLOAD_LABELS === 'true',
|
|
27
|
+
};
|
|
28
|
+
const profile = ['free', 'paid'].includes(env.DELIVERY_UPLOAD_PROFILE) ? env.DELIVERY_UPLOAD_PROFILE : 'unknown';
|
|
29
|
+
const declaredBuild = env.DELIVERY_UPLOAD_CONSUMER_BUILD;
|
|
30
|
+
const consumerBuildId = typeof declaredBuild === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,159}$/.test(declaredBuild)
|
|
31
|
+
? await sha256(declaredBuild) : null;
|
|
32
|
+
const uploadPipeline = {
|
|
33
|
+
schemaVersion: 1,
|
|
34
|
+
protocolVersion: 1,
|
|
35
|
+
profile,
|
|
36
|
+
certification: { status: 'unverified', reportId: null },
|
|
37
|
+
provenance: { source: 'installation-declared', consumerBuildId, verified: false },
|
|
38
|
+
features: { ...FEATURES },
|
|
39
|
+
limits: null,
|
|
40
|
+
admission: { status: 'unknown', budgetRevision: null },
|
|
41
|
+
};
|
|
42
|
+
const revision = await sha256(JSON.stringify({ policy: POLICY_REVISION, ...legacy, ...uploadPipeline }));
|
|
43
|
+
return { ok: true, ...legacy, uploadPipeline: { ...uploadPipeline, revision } };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// The new request namespace is fail-closed, even on a Paid installation. Legacy
|
|
47
|
+
// requests retain their existing limits, receipts and writer/integrity checks.
|
|
48
|
+
// A header opt-in is rejected before reading JSON; body opt-ins are checked by
|
|
49
|
+
// both upload routes before dispatch, including createPackage and activation.
|
|
50
|
+
export function rejectDisabledUploadPipeline(request, body) {
|
|
51
|
+
const optedIn = request.headers.has('X-Delivery-Upload-Protocol') ||
|
|
52
|
+
(body !== null && typeof body === 'object' &&
|
|
53
|
+
(REQUEST_MARKERS.some(key => Object.hasOwn(body, key)) || RESERVED_ACTIONS.has(body.action)));
|
|
54
|
+
if (!optedIn) return null;
|
|
55
|
+
return new Response(JSON.stringify({
|
|
56
|
+
ok: false,
|
|
57
|
+
error: 'La nuova pipeline di upload non è ancora abilitata. Rileggi le capability prima di proseguire.',
|
|
58
|
+
code: 'upload_capability_changed',
|
|
59
|
+
retryable: false,
|
|
60
|
+
}), {
|
|
61
|
+
status: 409,
|
|
62
|
+
headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
|
|
63
|
+
});
|
|
64
|
+
}
|