@lunora/do 1.0.0-alpha.244 → 1.0.0-alpha.246

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.
@@ -0,0 +1 @@
1
+ import{createShardKvStore as h,createShardAlarms as u}from"@lunora/platform-cloudflare";import{c as f}from"./constant-time-equal-BRh9yUCr.mjs";import{j as n}from"./json-response-0Bq2ky0N.mjs";const m=10080*60,S=2160*60*60,d=1440*60*1e3,E="x-lunora-session-do-secret",l="x-lunora-session-token",_=/^[\w-]+$/,g=32,N=256,T=256,v=(s,e)=>{const t=e.SESSION_DO_SECRET;if(typeof t!="string"||t.length===0)return!1;const r=s.headers.get(E);return typeof r!="string"||r.length===0?!1:f(t,r)},p=s=>{let e;if(s==null)e=m;else if(typeof s=="number")e=s;else return;if(!(!Number.isFinite(e)||!Number.isInteger(e)||e<=0||e>S))return e},k=s=>{if(typeof s=="string"&&!(s.length<g||s.length>N)&&_.test(s))return s};class A{state;env;kv;alarms;constructor(e,t){this.state=e,this.env=t,this.kv=h(e.storage),this.alarms=u(e.storage)}async fetch(e){const t=this.env??{};if(!v(e,t))return n({error:{code:"UNAUTHORIZED",message:"missing or invalid SessionDO secret"}},401);const r=new URL(e.url);return e.method==="POST"&&r.pathname==="/create"?this.handleCreate(e):e.method==="GET"&&r.pathname==="/get"?this.handleGet(e):e.method==="DELETE"&&r.pathname==="/revoke"?this.handleRevoke(e):n({error:{code:"NOT_FOUND",message:"no such session route"}},404)}async alarm(){if(typeof this.state.storage.list!="function")return;const e=Date.now(),t=await this.kv.list({prefix:"s:"}),r=[];let o=0;for(const[i,a]of t)a.expiresAt<e?r.push(i):o+=1;for(const i of r)await this.kv.delete(i);o>0&&await this.alarms.set(e+d)}async handleCreate(e){let t;try{t=await e.json()}catch{return n({error:"invalid_request"},400)}const r=k(t.token);if(r===void 0)return n({error:"invalid_request"},400);const{userId:o}=t;if(typeof o!="string"||o.length===0||o.length>T)return n({error:"invalid_request"},400);const i=p(t.ttlSeconds);if(i===void 0)return n({error:"invalid_request"},400);const a=Date.now(),c={createdAt:a,expiresAt:a+i*1e3,userId:o};return await this.kv.put(`s:${r}`,c),await this.armGcAlarm(),n({token:r,...c},201)}async armGcAlarm(){await this.alarms.get()===null&&await this.alarms.set(Date.now()+d)}async handleGet(e){const t=e.headers.get(l);if(!t)return n({error:{code:"INVALID_INPUT",message:"token required"}},400);const r=await this.kv.get(`s:${t}`);return r?r.expiresAt<Date.now()?(await this.kv.delete(`s:${t}`),n({error:{code:"EXPIRED",message:"session expired"}},404)):n({token:t,...r},200):n({error:{code:"NOT_FOUND",message:"session not found"}},404)}async handleRevoke(e){const t=e.headers.get(l);return t?(await this.kv.delete(`s:${t}`),n({ok:!0},200)):n({error:{code:"INVALID_INPUT",message:"token required"}},400)}}export{m as SESSION_DO_TTL_DEFAULT,A as SessionDO};
@@ -0,0 +1,2 @@
1
+ import{siblingSecretOf as b,RELAY_SIGNATURE_HEADER as c,verifySiblingBody as S,stubByName as w,signSiblingBody as p}from"@lunora/shard-engine";import{j as o}from"./json-response-0Bq2ky0N.mjs";const T=async(a,e)=>{if(!a.body)return"";const t=a.body.getReader(),r=new TextDecoder;let s=0,n="";for(;;){const{done:d,value:i}=await t.read();if(d)break;if(i){if(s+=i.byteLength,s>e)return await t.cancel().catch(()=>{}),null;n+=r.decode(i,{stream:!0})}}return n+=r.decode(),n},l=(a,e,t)=>{const{pathname:r,search:s}=new URL(e);return`${a.toUpperCase()} ${r}${s}
2
+ ${t}`},E=5e3,u=64*1024,_="__lunora_shard_registry__",R="s:",O="\0",y=2048,h=(a,e)=>`${R}${a}${O}${e}`,g=a=>{let e;try{const s=JSON.parse(a);if(s===null||typeof s!="object")throw new TypeError("not an object");e=s}catch{return{kind:"error",response:o({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}}const t=typeof e.table=="string"?e.table.trim():"",r=typeof e.shardKey=="string"?e.shardKey.trim():"";return!t||!r?{kind:"error",response:o({error:{code:"BAD_REQUEST",message:"table and shardKey required"}},400)}:new TextEncoder().encode(h(t,r)).length>y?{kind:"error",response:o({error:{code:"BAD_REQUEST",message:`table and shardKey exceed the ${String(y)}-byte storage key limit`}},400)}:{kind:"ok",value:{shardKey:r,table:t}}};class U{env;state;tables=new Map;loaded=!1;constructor(e,t){this.state=e,this.env=t}async fetch(e){const t=this.refuseUnsigned(e);if(t)return t;const r=await T(e,u);if(r===null)return o({error:{code:"PAYLOAD_TOO_LARGE",message:`shard registry requests are capped at ${String(u)} bytes`}},413);const s=await this.refuseBadSignature(e,r);if(s)return s;await this.ensureLoaded();const n=new URL(e.url);return e.method==="POST"&&n.pathname==="/register"?this.handleRegister(r):e.method==="POST"&&n.pathname==="/unregister"?this.handleUnregister(r):e.method==="GET"&&n.pathname==="/list"?this.handleList(n):e.method==="GET"&&n.pathname==="/snapshot"?this.handleSnapshot():o({error:{code:"NOT_FOUND",message:`unknown shard-registry route ${e.method} ${n.pathname}`}},404)}refuseUnsigned(e){if(b(this.env)===void 0)return o({error:{code:"FORBIDDEN",message:"the shard registry requires LUNORA_RELAY_SECRET to be set on the Durable Object's environment"}},403);if(!e.headers.has(c))return o({error:{code:"FORBIDDEN",message:"missing or invalid shard registry signature"}},403)}async refuseBadSignature(e,t){const r=l(e.method,e.url,t);if(!await S(this.env,e.headers.get(c),r))return o({error:{code:"FORBIDDEN",message:"missing or invalid shard registry signature"}},403)}async ensureLoaded(){this.loaded||await this.state.blockConcurrencyWhile(async()=>{if(this.loaded)return;const e=await this.state.storage.list({prefix:R});for(const t of e.values()){let r=this.tables.get(t.table);r||(r=new Set,this.tables.set(t.table,r)),r.add(t.shardKey)}this.loaded=!0})}handleList(e){const t=e.searchParams.get("table");return t?o({shardKeys:[...this.tables.get(t)??[]]},200):o({error:{code:"BAD_REQUEST",message:"missing required query parameter: table"}},400)}async handleRegister(e){const t=g(e);if(t.kind==="error")return t.response;const{shardKey:r,table:s}=t.value;return this.state.blockConcurrencyWhile(async()=>{let n=this.tables.get(s);return n?.has(r)?o({changed:!1,ok:!0},200):(await this.state.storage.put(h(s,r),{shardKey:r,table:s}),n||(n=new Set,this.tables.set(s,n)),n.add(r),o({changed:!0,ok:!0},200))})}handleSnapshot(){return o({tables:this.serializeTables()},200)}async handleUnregister(e){const t=g(e);if(t.kind==="error")return t.response;const{shardKey:r,table:s}=t.value;return this.state.blockConcurrencyWhile(async()=>{const n=this.tables.get(s);return n?.has(r)?(await this.state.storage.delete(h(s,r)),n.delete(r),n.size===0&&this.tables.delete(s),o({changed:!0,ok:!0},200)):o({changed:!1,ok:!0},200)})}serializeTables(){return Object.fromEntries([...this.tables].map(([e,t])=>[e,[...t]]))}}const m=async(a,e,t,r,s)=>{if(s===void 0)throw new Error("the shard registry requires LUNORA_RELAY_SECRET; set it on the worker and every Durable Object");const n=`https://shard-registry.internal${e}`,d=JSON.stringify({shardKey:r,table:t}),i=await a.fetch(n,{body:d,headers:{"content-type":"application/json",[c]:await p(s,l("POST",n,d))},method:"POST",signal:AbortSignal.timeout(E)});if(!i.ok)throw new Error(`shard registry ${e} returned ${String(i.status)}: ${await i.text()}`)},A=async(a,e,t,r)=>m(a,"/register",e,t,r),D=async(a,e,t,r)=>m(a,"/unregister",e,t,r),f=async(a,e,t)=>{if(t===void 0)throw new Error("the shard registry requires LUNORA_RELAY_SECRET; set it on the worker and every Durable Object");const r=`https://shard-registry.internal${e}`,s=await a.fetch(r,{headers:{[c]:await p(t,l("GET",r,""))},method:"GET",signal:AbortSignal.timeout(E)});if(!s.ok)throw new Error(`shard registry ${e.split("?")[0]??e} returned ${String(s.status)}: ${await s.text()}`);return await s.json()},k=a=>{const e=a;return typeof e?.register=="function"&&typeof e.unregister=="function"},N=a=>!k(a)&&typeof a=="object"&&a!==null&&"idFromName"in a&&typeof a.idFromName=="function",B=(a,e)=>{const t=()=>{const s=typeof a=="object"&&a!==null&&"SHARD_REGISTRY"in a?a.SHARD_REGISTRY:void 0,n=w(s,_,e);if(n===void 0)throw new Error("the shard registry entrypoint needs this worker's Durable Object namespace bound as SHARD_REGISTRY");return n},r=()=>b(a);return{listShardKeys:async s=>(await f(t(),`/list?table=${encodeURIComponent(s)}`,r())).shardKeys,register:async(s,n)=>A(t(),s,n,r()),snapshot:async()=>(await f(t(),"/snapshot",r())).tables,unregister:async(s,n)=>D(t(),s,n,r())}};export{_ as SHARD_REGISTRY_DO_NAME,U as ShardRegistryDO,B as hostedShardRegistry,N as isRegistryNamespace,k as isRegistryRpc,A as registerShardKey,D as unregisterShardKey};
@@ -0,0 +1 @@
1
+ const r=(e,n)=>{const c=Math.max(e.length,n.length);let h=e.length^n.length;for(let t=0;t<c;t+=1){const l=t<e.length?e.charCodeAt(t):0,o=t<n.length?n.charCodeAt(t):0;h|=l^o}return h===0};export{r as c};
@@ -0,0 +1 @@
1
+ const a=(n,s=200,o)=>{const e=new Headers({"content-type":"application/json"});for(const[t,r]of Object.entries(o??{}))e.set(t,r);return Response.json(n,{headers:e,status:s})};export{a as j};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/do",
3
- "version": "1.0.0-alpha.244",
3
+ "version": "1.0.0-alpha.246",
4
4
  "description": "Lunora Durable Objects: ShardDO (SQLite, OCC, hibernated WebSocket subscriptions) and SessionDO",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -47,10 +47,10 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
50
- "@lunora/observability": "1.0.0-alpha.168",
51
- "@lunora/platform": "1.0.0-alpha.74",
52
- "@lunora/platform-cloudflare": "1.0.0-alpha.107",
53
- "@lunora/shard-engine": "1.0.0-alpha.157",
50
+ "@lunora/observability": "1.0.0-alpha.170",
51
+ "@lunora/platform": "1.0.0-alpha.75",
52
+ "@lunora/platform-cloudflare": "1.0.0-alpha.108",
53
+ "@lunora/shard-engine": "1.0.0-alpha.158",
54
54
  "@lunora/values": "1.0.0-alpha.80",
55
55
  "@lunora/wire": "1.0.0-alpha.2",
56
56
  "drizzle-orm": "1.0.0-rc.5"
@@ -1 +0,0 @@
1
- import{createShardKvStore as h,createShardAlarms as u}from"@lunora/platform-cloudflare";import{j as n,c as f}from"./json-response-BqTX3KmR.mjs";const S=10080*60,E=2160*60*60,d=1440*60*1e3,m="x-lunora-session-do-secret",l="x-lunora-session-token",_=/^[\w-]+$/,g=32,N=256,T=256,v=(s,e)=>{const t=e.SESSION_DO_SECRET;if(typeof t!="string"||t.length===0)return!1;const r=s.headers.get(m);return typeof r!="string"||r.length===0?!1:f(t,r)},p=s=>{let e;if(s==null)e=S;else if(typeof s=="number")e=s;else return;if(!(!Number.isFinite(e)||!Number.isInteger(e)||e<=0||e>E))return e},k=s=>{if(typeof s=="string"&&!(s.length<g||s.length>N)&&_.test(s))return s};class I{state;env;kv;alarms;constructor(e,t){this.state=e,this.env=t,this.kv=h(e.storage),this.alarms=u(e.storage)}async fetch(e){const t=this.env??{};if(!v(e,t))return n({error:{code:"UNAUTHORIZED",message:"missing or invalid SessionDO secret"}},401);const r=new URL(e.url);return e.method==="POST"&&r.pathname==="/create"?this.handleCreate(e):e.method==="GET"&&r.pathname==="/get"?this.handleGet(e):e.method==="DELETE"&&r.pathname==="/revoke"?this.handleRevoke(e):n({error:{code:"NOT_FOUND",message:"no such session route"}},404)}async alarm(){if(typeof this.state.storage.list!="function")return;const e=Date.now(),t=await this.kv.list({prefix:"s:"}),r=[];let o=0;for(const[i,a]of t)a.expiresAt<e?r.push(i):o+=1;for(const i of r)await this.kv.delete(i);o>0&&await this.alarms.set(e+d)}async handleCreate(e){let t;try{t=await e.json()}catch{return n({error:"invalid_request"},400)}const r=k(t.token);if(r===void 0)return n({error:"invalid_request"},400);const{userId:o}=t;if(typeof o!="string"||o.length===0||o.length>T)return n({error:"invalid_request"},400);const i=p(t.ttlSeconds);if(i===void 0)return n({error:"invalid_request"},400);const a=Date.now(),c={createdAt:a,expiresAt:a+i*1e3,userId:o};return await this.kv.put(`s:${r}`,c),await this.armGcAlarm(),n({token:r,...c},201)}async armGcAlarm(){await this.alarms.get()===null&&await this.alarms.set(Date.now()+d)}async handleGet(e){const t=e.headers.get(l);if(!t)return n({error:{code:"INVALID_INPUT",message:"token required"}},400);const r=await this.kv.get(`s:${t}`);return r?r.expiresAt<Date.now()?(await this.kv.delete(`s:${t}`),n({error:{code:"EXPIRED",message:"session expired"}},404)):n({token:t,...r},200):n({error:{code:"NOT_FOUND",message:"session not found"}},404)}async handleRevoke(e){const t=e.headers.get(l);return t?(await this.kv.delete(`s:${t}`),n({ok:!0},200)):n({error:{code:"INVALID_INPUT",message:"token required"}},400)}}export{S as SESSION_DO_TTL_DEFAULT,I as SessionDO};
@@ -1 +0,0 @@
1
- import{S as s,a as S,r as t,u as i}from"./shard-registry-do-DVfOqeqi.mjs";import"./json-response-BqTX3KmR.mjs";export{s as SHARD_REGISTRY_DO_NAME,S as ShardRegistryDO,t as registerShardKey,i as unregisterShardKey};
@@ -1 +0,0 @@
1
- const a=(t,n)=>{const s=Math.max(t.length,n.length);let o=t.length^n.length;for(let e=0;e<s;e+=1){const c=e<t.length?t.charCodeAt(e):0,r=e<n.length?n.charCodeAt(e):0;o|=c^r}return o===0},h=(t,n=200,s)=>{const o=new Headers({"content-type":"application/json"});for(const[e,c]of Object.entries(s??{}))o.set(e,c);return Response.json(t,{headers:o,status:n})};export{a as c,h as j};
@@ -1 +0,0 @@
1
- import{c as g,j as n}from"./json-response-BqTX3KmR.mjs";const y=(a,t,e)=>{if(typeof e!="string"||e.length===0)return!0;const r=a.headers.get(t);return r!==null&&r.length>0&&g(e,r)},l="x-lunora-shard-registry-do-secret",E="SHARD_REGISTRY_DO_SECRET",S=5e3,f="__lunora_shard_registry__",c="s:",b="\0",h=2048,o=(a,t)=>`${c}${a}${b}${t}`,d=async a=>{let t;try{t=await a.json()}catch{return{kind:"error",response:n({error:{code:"BAD_REQUEST",message:"invalid JSON body"}},400)}}const e=typeof t.table=="string"?t.table.trim():"",r=typeof t.shardKey=="string"?t.shardKey.trim():"";return!e||!r?{kind:"error",response:n({error:{code:"BAD_REQUEST",message:"table and shardKey required"}},400)}:new TextEncoder().encode(o(e,r)).length>h?{kind:"error",response:n({error:{code:"BAD_REQUEST",message:`table and shardKey exceed the ${String(h)}-byte storage key limit`}},400)}:{kind:"ok",value:{shardKey:r,table:e}}};class p{env;state;tables=new Map;loaded=!1;constructor(t,e){this.state=t,this.env=e}async fetch(t){if(!y(t,l,this.env?.[E]))return n({error:{code:"UNAUTHORIZED",message:"missing or invalid shard registry secret"}},401);await this.ensureLoaded();const e=new URL(t.url);return t.method==="POST"&&e.pathname==="/register"?this.handleRegister(t):t.method==="POST"&&e.pathname==="/unregister"?this.handleUnregister(t):t.method==="GET"&&e.pathname==="/list"?this.handleList(e):t.method==="GET"&&e.pathname==="/snapshot"?this.handleSnapshot():n({error:{code:"NOT_FOUND",message:`unknown shard-registry route ${t.method} ${e.pathname}`}},404)}async ensureLoaded(){this.loaded||await this.state.blockConcurrencyWhile(async()=>{if(this.loaded)return;const t=await this.state.storage.list({prefix:c});for(const e of t.values()){let r=this.tables.get(e.table);r||(r=new Set,this.tables.set(e.table,r)),r.add(e.shardKey)}this.loaded=!0})}handleList(t){const e=t.searchParams.get("table");return e?n({shardKeys:[...this.tables.get(e)??[]]},200):n({error:{code:"BAD_REQUEST",message:"missing required query parameter: table"}},400)}async handleRegister(t){const e=await d(t);if(e.kind==="error")return e.response;const{shardKey:r,table:i}=e.value;return this.state.blockConcurrencyWhile(async()=>{let s=this.tables.get(i);return s?.has(r)?n({changed:!1,ok:!0},200):(await this.state.storage.put(o(i,r),{shardKey:r,table:i}),s||(s=new Set,this.tables.set(i,s)),s.add(r),n({changed:!0,ok:!0},200))})}handleSnapshot(){return n({tables:this.serializeTables()},200)}async handleUnregister(t){const e=await d(t);if(e.kind==="error")return e.response;const{shardKey:r,table:i}=e.value;return this.state.blockConcurrencyWhile(async()=>{const s=this.tables.get(i);return s?.has(r)?(await this.state.storage.delete(o(i,r)),s.delete(r),s.size===0&&this.tables.delete(i),n({changed:!0,ok:!0},200)):n({changed:!1,ok:!0},200)})}serializeTables(){return Object.fromEntries([...this.tables].map(([t,e])=>[t,[...e]]))}}const u=async(a,t,e,r,i)=>{const s=await a.fetch(`https://shard-registry.internal${t}`,{body:JSON.stringify({shardKey:r,table:e}),headers:{"content-type":"application/json",...i?{[l]:i}:{}},method:"POST",signal:AbortSignal.timeout(S)});if(!s.ok)throw new Error(`shard registry ${t} returned ${String(s.status)}: ${await s.text()}`)},m=async(a,t,e,r)=>u(a,"/register",t,e,r),T=async(a,t,e,r)=>u(a,"/unregister",t,e,r);export{f as S,p as a,E as b,m as r,T as u};