@cardinali-studio/adminkit 2.2.47 → 2.2.48

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/README.md CHANGED
@@ -309,3 +309,22 @@ consumers must remove the old internal `setSiteConfig` workaround.
309
309
  ### Illustrated Transfer guide (2.2.44)
310
310
 
311
311
  The dashboard links to the bundled Italian guide in a new tab. Both public admin mount functions recognize `?adminkit-guide=transfer` on the existing protected admin path. The reader loads lazily, has no Transfer API hooks, supports chapter deep links and contains seven locally captured screenshots with synthetic data. Screenshots and guide CSS ship in `dist/app/guide/`; consumers using Vite bundle the relative image URLs automatically. No external documentation host, new route or credentials are required. Source and screenshot provenance: `src/app/guide/` and `scripts/preview-transfer-guide.mjs`.
312
+
313
+ ### Cloudflare Email Service and shared B2 buckets
314
+
315
+ Transfer email also supports `DELIVERY_EMAIL_PROVIDER=cloudflare`, the native
316
+ `DELIVERY_EMAIL` send binding and `DELIVERY_EMAIL_ENABLED=true`. Set
317
+ `ENVIRONMENT=production`, a verified `DELIVERY_EMAIL_FROM`, the canonical
318
+ `DELIVERY_PUBLIC_BASE` and the stable `DELIVERY_SECRET`; save owner/preferences
319
+ in Transfer settings. Request and cron Workers need the same configuration.
320
+ No Resend key is required. Use a binding restricted by sender (not only by owner
321
+ recipient) to send customer links on Workers Paid. Explicit provider selection
322
+ never falls back to Resend. Unknown/timeout results require review to prevent
323
+ unsafe automatic duplicate sends; documented rate/quota rejections can retry.
324
+ Non-production tests must inject an explicit mock binding.
325
+
326
+ `DELIVERY_STORAGE_PREFIX=deliveries/consumer-a` optionally isolates object keys,
327
+ signed URLs, inventories and version-aware deletion in a shared private bucket.
328
+ Independent projects must keep separate transfer databases. Consumers omitting
329
+ the setting retain existing paths. Keep the cleanup migration and persistent
330
+ cleanup records so outstanding signed writes are collected after deletion.
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  const enc = new TextEncoder();
9
+ import {deliveryStorageScope} from './delivery-storage-scope.js';
9
10
 
10
11
  export function b2Configured(env) {
11
12
  return !!(env.B2_ENDPOINT && env.B2_REGION && env.B2_BUCKET &&
@@ -17,6 +18,7 @@ export function b2ObjectKey(prefix, filename) {
17
18
  }
18
19
 
19
20
  export async function b2Request(env, method, key, options = {}) {
21
+ options = {...options, query: deliveryStorageScope(env, method.toUpperCase(), key, options.query)};
20
22
  assertConfig(env);
21
23
  const url = objectUrl(env, key);
22
24
  addQuery(url, options.query);
@@ -72,6 +74,7 @@ export async function b2PresignGetObject(env, key, options = {}) {
72
74
  }
73
75
 
74
76
  async function presignObject(env, method, key, query, expires, maxExpires) {
77
+ query = deliveryStorageScope(env, method, key, query);
75
78
  assertConfig(env);
76
79
  const url = objectUrl(env, key);
77
80
  addQuery(url, query);
@@ -193,10 +196,28 @@ export function b2Get(env, key, range) {
193
196
  export async function b2Head(env, key) {
194
197
  const res = await b2Request(env, "HEAD", key);
195
198
  if (res.status === 404) return null;
199
+ if ([403, 500, 502, 503, 504].includes(res.status)) {
200
+ // Some edge paths reject HEAD while the same SigV4 GET succeeds. Request
201
+ // exactly one byte and validate Content-Range; never buffer a whole ZIP.
202
+ await res.body?.cancel();
203
+ return b2RangeMetadata(env, key);
204
+ }
196
205
  if (!res.ok) throw new Error(`B2 head ${res.status}`);
197
206
  return { bytes: Number(res.headers.get("content-length")), etag: (res.headers.get("etag") || "").replaceAll('"', "") };
198
207
  }
199
208
 
209
+ export async function b2RangeMetadata(env, key) {
210
+ const partial = await b2Request(env, "GET", key, {headers: {Range: "bytes=0-0"}});
211
+ const range = /^bytes 0-0\/(\d+)$/.exec(partial.headers.get("content-range") || "");
212
+ await partial.body?.cancel();
213
+ if (partial.status === 404) return null;
214
+ const bytes = Number(range?.[1]);
215
+ if (partial.status !== 206 || !range || !Number.isSafeInteger(bytes) || bytes < 1) {
216
+ throw new Error(`B2 metadata range ${partial.status}`);
217
+ }
218
+ return {bytes, etag: (partial.headers.get("etag") || "").replaceAll('"', "")};
219
+ }
220
+
200
221
  /** ETag multipart S3: MD5 dei digest binari delle parti. MD5 è supportato da Workers
201
222
  * per interoperabilità; non viene usato per autenticazione o hashing di segreti. */
202
223
  export async function multipartEtag(parts) {
@@ -0,0 +1,44 @@
1
+ /* Provider boundary. Never fall back between providers after an attempted send. */
2
+ export function deliveryEmailProvider(env) {
3
+ return env.DELIVERY_EMAIL_PROVIDER ?? (env.RESEND_API_KEY ? 'resend' : 'disabled');
4
+ }
5
+ export function deliveryEmailProviderConfigured(env) {
6
+ const provider = deliveryEmailProvider(env);
7
+ return provider === 'cloudflare' ? typeof env.DELIVERY_EMAIL?.send === 'function'
8
+ : provider === 'resend' && !!env.RESEND_API_KEY;
9
+ }
10
+ export async function sendCloudflareDeliveryEmail(binding, payload, {timeoutMs = 15000} = {}) {
11
+ let timeout;
12
+ try {
13
+ // Snapshots retain the provider-neutral contents and the historical Resend
14
+ // envelope. Map only known fields; no arbitrary headers or attachments.
15
+ const match = /^(.*?) <([^<>]+)>$/.exec(payload.from);
16
+ const message = {
17
+ from: match ? {name: match[1], email: match[2]} : payload.from,
18
+ to: payload.to, subject: payload.subject, text: payload.text, html: payload.html,
19
+ ...(payload.reply_to ? {replyTo: payload.reply_to} : {}),
20
+ };
21
+ const result = await Promise.race([
22
+ Promise.resolve().then(() => binding.send(message)),
23
+ new Promise((_, reject) => { timeout = setTimeout(() => reject(Error('send_timeout')), timeoutMs); }),
24
+ ]);
25
+ return result && typeof result.messageId === 'string' && result.messageId
26
+ ? {state: 'sent', id: result.messageId, code: null}
27
+ : {state: 'review', id: null, code: 'cloudflare_unknown'};
28
+ } catch (error) {
29
+ if (['E_RATE_LIMIT_EXCEEDED', 'E_DAILY_LIMIT_EXCEEDED'].includes(error?.code)) {
30
+ return {state: 'pending', id: null, code: 'cloudflare_retryable'};
31
+ }
32
+ if (['E_VALIDATION_ERROR', 'E_FIELD_MISSING', 'E_TOO_MANY_RECIPIENTS',
33
+ 'E_SENDER_NOT_VERIFIED', 'E_RECIPIENT_NOT_ALLOWED', 'E_RECIPIENT_SUPPRESSED',
34
+ 'E_ACCOUNT_SUSPENDED', 'E_SENDER_DOMAIN_NOT_AVAILABLE', 'E_CONTENT_TOO_LARGE',
35
+ 'E_HEADER_NOT_ALLOWED', 'E_HEADER_USE_API_FIELD', 'E_HEADER_VALUE_INVALID',
36
+ 'E_HEADER_VALUE_TOO_LONG', 'E_HEADER_NAME_INVALID', 'E_HEADERS_TOO_LARGE',
37
+ 'E_HEADERS_TOO_MANY'].includes(error?.code)) {
38
+ return {state: 'failed', id: null, code: 'provider_rejected'};
39
+ }
40
+ // The binding cannot cancel an in-flight send or accept an idempotency key.
41
+ // A late response, internal failure or lost acknowledgement requires review.
42
+ return {state: 'review', id: null, code: 'cloudflare_unknown'};
43
+ } finally { clearTimeout(timeout); }
44
+ }
@@ -1,6 +1,7 @@
1
1
  /* Authenticated transfer emails. Consumers call the interceptor AFTER their usual
2
2
  * Access/JWT/origin checks. Cron drains only explicitly queued notifications. */
3
3
  import {seal,unseal,sha256} from './delivery-crypto.js';
4
+ import {deliveryEmailProvider,deliveryEmailProviderConfigured,sendCloudflareDeliveryEmail} from './delivery-email-provider.js';
4
5
  const headers={'Content-Type':'application/json','Cache-Control':'private, no-store','X-Robots-Tag':'noindex, nofollow'};
5
6
  const json=(body,status=200)=>new Response(JSON.stringify(body),{status,headers});
6
7
  const fail=(text,status=400)=>Object.assign(new Error(text),{status});
@@ -11,7 +12,7 @@ export async function deliveryEmailConfiguration(env){
11
12
  const settingsEditable=!!env.DB&&!!await env.DB.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='delivery_email_settings'").first();
12
13
  if(settingsEditable){const row=await env.DB.prepare('SELECT * FROM delivery_email_settings WHERE singleton=1').first();if(row){owner=row.owner_email;version=Number(row.version);notifyDownloads=!!row.notify_downloads;notifyReady=row.notify_ready!==0;}}
13
14
  let base;try{base=new URL(env.DELIVERY_PUBLIC_BASE);}catch{}
14
- const enabled=env.DELIVERY_EMAIL_ENABLED==='true'&&!!env.RESEND_API_KEY&&validDeliveryEmail(from)&&!!env.DELIVERY_SECRET&&base?.protocol==='https:'&&!base.username&&!base.password&&!base.search&&!base.hash&&base.pathname==='/';
15
+ const enabled=env.DELIVERY_EMAIL_ENABLED==='true'&&deliveryEmailProviderConfigured(env)&&validDeliveryEmail(from)&&!!env.DELIVERY_SECRET&&base?.protocol==='https:'&&!base.username&&!base.password&&!base.search&&!base.hash&&base.pathname==='/';
15
16
  return {enabled,ownerEnabled:enabled&&validDeliveryEmail(owner),ownerEmail:validDeliveryEmail(owner)?owner:'',fromEmail:validDeliveryEmail(from)?from:'',settingsVersion:version,settingsEditable,notifyDownloads,notifyReady};
16
17
  }
17
18
  export async function saveDeliveryEmailSettings(env,body){
@@ -108,25 +109,38 @@ export async function queueDownloadNotifications(env){
108
109
  }
109
110
  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();
110
111
  }
111
- export async function processDeliveryEmails(env,{limit=2,fetch:send=globalThis.fetch}={}){
112
+ export async function processDeliveryEmails(env,{limit=2,fetch:send=globalThis.fetch,email,timeoutMs}={}){
112
113
  if(env.DELIVERY_EMAIL_ENABLED!=='true')return;
114
+ const provider=deliveryEmailProvider(env);
115
+ // Local/staging callers must explicitly inject a test binding. A remote binding
116
+ // accidentally present in a development environment must never send mail.
117
+ const binding=email??(env.ENVIRONMENT==='production'?env.DELIVERY_EMAIL:undefined);
118
+ if(provider==='cloudflare'&&!binding)return;
113
119
  if(!(await deliveryEmailConfiguration(env)).enabled||!await installed(env))return;
114
120
  await queueDownloadNotifications(env);
115
121
  const now=new Date().toISOString();const {results}=await env.DB.prepare(`SELECT * FROM delivery_email_outbox WHERE (state='pending' AND next_attempt_at<=?) OR (state='sending' AND lease_until<=?) ORDER BY created_at LIMIT ?`).bind(now,now,Math.max(1,Math.min(limit,10))).all();
116
122
  for(const job of results||[]){
123
+ if((provider==='cloudflare'&&job.attempts>0&&!(job.state==='pending'&&job.error_code==='cloudflare_retryable'))
124
+ ||(provider!=='cloudflare'&&job.error_code?.startsWith('cloudflare_'))){
125
+ await env.DB.prepare("UPDATE delivery_email_outbox SET state='review',error_code='verify_before_retry',lease_until=NULL,lease_token=NULL WHERE id=? AND ((state='pending' AND next_attempt_at<=?) OR (state='sending' AND lease_until<=?))").bind(job.id,now,now).run();continue;
126
+ }
117
127
  // Resend retains idempotency keys 24h: never retry an uncertain send afterwards.
118
128
  if(job.first_attempt_at&&Date.now()-Date.parse(job.first_attempt_at)>23*3600000){await env.DB.prepare("UPDATE delivery_email_outbox SET state='review',error_code='verify_before_retry' WHERE id=? AND state IN ('pending','sending')").bind(job.id).run();continue;}
119
- const claim=crypto.randomUUID(),lease=new Date(Date.now()+120000).toISOString();const won=await env.DB.prepare(`UPDATE delivery_email_outbox SET state='sending',lease_token=?,lease_until=?,attempts=attempts+1,first_attempt_at=COALESCE(first_attempt_at,?) WHERE id=? AND ((state='pending' AND next_attempt_at<=?) OR (state='sending' AND lease_until<=?))`).bind(claim,lease,now,job.id,now,now).run();if(!won.meta?.changes)continue;
129
+ const claim=crypto.randomUUID(),lease=new Date(Date.now()+120000).toISOString();const won=await env.DB.prepare(`UPDATE delivery_email_outbox SET state='sending',lease_token=?,lease_until=?,attempts=attempts+1,first_attempt_at=COALESCE(first_attempt_at,?),error_code=? WHERE id=? AND ((state='pending' AND next_attempt_at<=?) OR (state='sending' AND lease_until<=?))`).bind(claim,lease,now,provider==='cloudflare'?'cloudflare_sending':job.error_code,job.id,now,now).run();if(!won.meta?.changes)continue;
120
130
  try{
121
131
  const isDownload=job.generation.startsWith('download:');
122
132
  const s=isDownload?await downloadSnapshot(env,job.delivery_id,job.link_id):await snapshot(env,job.delivery_id),p=await prefs(env,job.delivery_id),c=(await deliveryEmailConfiguration(env));
123
133
  if(!s||s.link.id!==job.link_id||(!isDownload&&s.generation!==job.generation)||(job.kind==='owner'?((isDownload?!c.notifyDownloads:!c.notifyReady)||job.recipient!==c.ownerEmail):(!p.send_recipient||job.recipient!==p.recipient_email))){await finish('cancelled',null,'cancelled');continue;}
124
134
  const current=await env.DB.prepare("SELECT id FROM delivery_email_outbox WHERE id=? AND state='sending' AND lease_token=?").bind(job.id,claim).first();if(!current)continue;
125
135
  const payload=await unseal(env.DELIVERY_SECRET,job.payload_ciphertext);
136
+ if(provider==='cloudflare'){
137
+ const result=await sendCloudflareDeliveryEmail(binding,JSON.parse(payload),{timeoutMs});
138
+ await finish(result.state,result.id,result.code);continue;
139
+ }
126
140
  const r=await send('https://api.resend.com/emails',{method:'POST',headers:{Authorization:'Bearer '+env.RESEND_API_KEY,'Content-Type':'application/json','Idempotency-Key':'transfer/'+job.id},body:payload,signal:AbortSignal.timeout(15000)});
127
141
  const body=await r.json().catch(()=>({}));if(r.ok&&typeof body.id==='string'){await finish('sent',body.id,null);continue;}
128
142
  const retry=r.status===429||r.status>=500;await finish(retry?'pending':'failed',null,retry?'temporary_error':'provider_rejected');
129
- }catch{await finish('pending',null,'temporary_error');}
143
+ }catch{await finish(provider==='cloudflare'?'review':'pending',null,provider==='cloudflare'?'cloudflare_unknown':'temporary_error');}
130
144
  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();}
131
145
  }
132
146
  }
@@ -0,0 +1,27 @@
1
+ /* Optional physical namespace for consumers sharing one private bucket. */
2
+ export function deliveryStorageRoot(env) {
3
+ if (env.DELIVERY_STORAGE_PREFIX === undefined) return 'deliveries';
4
+ const prefix = env.DELIVERY_STORAGE_PREFIX;
5
+ if (typeof prefix !== 'string' || !/^deliveries\/[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(prefix)) {
6
+ throw Error('Invalid delivery storage prefix');
7
+ }
8
+ return prefix;
9
+ }
10
+ export function deliveryStorageScope(env, method, key, query) {
11
+ if (env.DELIVERY_STORAGE_PREFIX === undefined) return query;
12
+ const scope = deliveryStorageRoot(env) + '/';
13
+ const valid = value => typeof value === 'string' && value.startsWith(scope)
14
+ && !value.split('/').some(part => part === '.' || part === '..') && !value.includes('\\');
15
+ if (key) {
16
+ if (!valid(key)) throw Error('Delivery storage scope denied');
17
+ return query;
18
+ }
19
+ // Bucket-level reads must be bounded to this namespace as well. This covers
20
+ // version inventories, incomplete multipart listings and purge listings.
21
+ if (method !== 'GET' || !query || !('versions' in query || 'uploads' in query || 'list-type' in query)) {
22
+ throw Error('Unscoped bucket request denied');
23
+ }
24
+ const prefix = query.prefix ?? scope;
25
+ if (!valid(prefix)) throw Error('Delivery storage listing scope denied');
26
+ return {...query, prefix};
27
+ }
@@ -10,6 +10,7 @@ import { readDeliveryDashboard, verifyDeliveryStorage } from "../_shared/deliver
10
10
  */
11
11
 
12
12
  import { b2ObjectKey, b2PutSmall } from "../_shared/b2.js";
13
+ import {deliveryStorageRoot} from '../_shared/delivery-storage-scope.js';
13
14
  import { validateDeliverySourceBytes, validateDeliveryManifestV1 } from "../_shared/delivery-limits.js";
14
15
  import { DELIVERY_LINK_MIN_LENGTH, DELIVERY_LINK_TOKEN_BYTES, randomToken, seal, sha256, unseal } from "../_shared/delivery-crypto.js";
15
16
  /* Il lavoro di cancellazione sta in _shared perché lo condivide con il cron:
@@ -309,7 +310,7 @@ async function createPackage(env, body) {
309
310
  .bind(deliveryId).first();
310
311
  if (!delivery) throw new InputError("Transfer non trovato");
311
312
  const id = crypto.randomUUID();
312
- const prefix = `deliveries/${deliveryId}/${id}/v1`;
313
+ const prefix = `${deliveryStorageRoot(env)}/${deliveryId}/${id}/v1`;
313
314
  const now = new Date().toISOString();
314
315
  const pos = await env.DB.prepare(
315
316
  "SELECT COALESCE(MAX(position),-1)+1 n FROM delivery_packages WHERE delivery_id=?"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cardinali-studio/adminkit",
3
- "version": "2.2.47",
3
+ "version": "2.2.48",
4
4
  "type": "module",
5
5
  "description": "Motore riusabile di un pannello di amministrazione per siti Hugo su Cloudflare Pages: codec del front matter guidato dallo schema, form React, libreria media su R2. NIENTE di specifico di un sito qui dentro.",
6
6
  "license": "0BSD",