@lunora/server 1.0.0-alpha.8 → 1.0.0-alpha.80
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/LICENSE.md +219 -0
- package/README.md +46 -0
- package/dist/data-model.d.mts +260 -164
- package/dist/data-model.d.ts +260 -164
- package/dist/data-model.mjs +0 -1
- package/dist/drizzle.mjs +1 -1
- package/dist/index.d.mts +1989 -1173
- package/dist/index.d.ts +1989 -1173
- package/dist/index.mjs +1 -28
- package/dist/otel.d.mts +543 -0
- package/dist/otel.d.ts +543 -0
- package/dist/otel.mjs +1 -0
- package/dist/packem_shared/DEFAULT_LIMIT-B947Pbij.mjs +1 -0
- package/dist/packem_shared/LunoraEnvError-CjFbbR9t.mjs +3 -0
- package/dist/packem_shared/LunoraError-DcKdk9Ti.mjs +1 -0
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-C-McIltl.mjs +1 -0
- package/dist/packem_shared/allowAll-DkRAgItV.mjs +1 -0
- package/dist/packem_shared/asBucketStorage-BthCnWop.mjs +1 -0
- package/dist/packem_shared/bindOrm-lWdeDi9P.mjs +1 -0
- package/dist/packem_shared/buildMaskRegistry-72SL8fJn.mjs +1 -0
- package/dist/packem_shared/buildRlsReadRegistry-Deq8inqS.mjs +1 -0
- package/dist/packem_shared/composePluginMiddleware-DQHF6mYr.mjs +1 -0
- package/dist/packem_shared/context-identity-B2XYGA0B.mjs +1 -0
- package/dist/packem_shared/createPolicyDsl-DNfByAUX.mjs +1 -0
- package/dist/packem_shared/createSecrets-CyrEddTF.mjs +1 -0
- package/dist/packem_shared/defineAggregateIndex-BtVAy69G.mjs +1 -0
- package/dist/packem_shared/defineIdentity-DwkNKwYa.mjs +1 -0
- package/dist/packem_shared/defineMigration-7GI9Qbtd.mjs +1 -0
- package/dist/packem_shared/defineMutator-DKy8UtbB.mjs +1 -0
- package/dist/packem_shared/defineShape-DYxbNl5W.mjs +1 -0
- package/dist/packem_shared/defineStorageRule-BvxHVq3b.mjs +1 -0
- package/dist/packem_shared/functions-B2-H4PQT.mjs +1 -0
- package/dist/packem_shared/httpAction-Ddi7f0t6.mjs +5 -0
- package/dist/packem_shared/initLunora-CRypyq1P.mjs +1 -0
- package/dist/packem_shared/mask-CfHNITgg.mjs +1 -0
- package/dist/packem_shared/middleware-DEW0yLvU.mjs +1 -0
- package/dist/packem_shared/onConnect-BLRoOpv2.mjs +1 -0
- package/dist/packem_shared/onQueryChange-gepYD6KC.mjs +1 -0
- package/dist/packem_shared/plugin-DQcLxTx1.mjs +1 -0
- package/dist/packem_shared/policy-tag-D4RzgQnw.mjs +1 -0
- package/dist/packem_shared/protectPublic-Bo4G9xaV.mjs +1 -0
- package/dist/packem_shared/rls-B3mNGBuc.mjs +1 -0
- package/dist/packem_shared/run-middleware-B-JeGGp9.mjs +1 -0
- package/dist/packem_shared/storageRules-CTnby6M1.mjs +1 -0
- package/dist/packem_shared/types.d-B-pIn8rE.d.mts +141 -0
- package/dist/packem_shared/types.d-CdPDEjhz.d.ts +141 -0
- package/dist/rls/testing.d.mts +31 -31
- package/dist/rls/testing.d.ts +31 -31
- package/dist/rls/testing.mjs +1 -49
- package/dist/types.d.mts +1552 -506
- package/dist/types.d.ts +1552 -506
- package/dist/types.mjs +1 -31
- package/package.json +17 -4
- package/dist/packem_shared/LunoraEnvError-DjFkpkSP.mjs +0 -187
- package/dist/packem_shared/LunoraError-DhggBJZF.mjs +0 -51
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-C7j9gY_d.mjs +0 -114
- package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
- package/dist/packem_shared/bindOrm-Ce57S3N9.mjs +0 -128
- package/dist/packem_shared/buildRlsReadRegistry-CkxuS69B.mjs +0 -107
- package/dist/packem_shared/composePluginMiddleware-Ck5_TUO8.mjs +0 -100
- package/dist/packem_shared/createPolicyDsl-De67zPDS.mjs +0 -29
- package/dist/packem_shared/createSecrets-TsIP9lOa.mjs +0 -55
- package/dist/packem_shared/defineAggregateIndex-ZdyU78gh.mjs +0 -291
- package/dist/packem_shared/defineMigration-CAJLr6fx.mjs +0 -8
- package/dist/packem_shared/defineMutator-EIXAWhs9.mjs +0 -11
- package/dist/packem_shared/defineShape-CJ27Wx7o.mjs +0 -17
- package/dist/packem_shared/defineStorageRule-qu0mpilX.mjs +0 -20
- package/dist/packem_shared/functions-Di9FUNkf.mjs +0 -5
- package/dist/packem_shared/httpAction-B7FYUEgr.mjs +0 -340
- package/dist/packem_shared/initLunora-lxwHTEV3.mjs +0 -100
- package/dist/packem_shared/mask-eCUYOwhd.mjs +0 -211
- package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
- package/dist/packem_shared/policy-tag-DvpVH2tv.mjs +0 -13
- package/dist/packem_shared/protectPublic-BjFkQ_Or.mjs +0 -15
- package/dist/packem_shared/rls-ClmjkkxZ.mjs +0 -569
- package/dist/packem_shared/run-middleware-CYQOuoV6.mjs +0 -18
- package/dist/packem_shared/storageRules-4a30FSpI.mjs +0 -88
- package/dist/packem_shared/types.d-BDY0FYHK.d.ts +0 -135
- package/dist/packem_shared/types.d-DmvyEMD6.d.mts +0 -135
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{toErrorBody as S}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as k}from"@lunora/values";import{Hono as _}from"hono";import{LunoraError as p}from"./LunoraError-DcKdk9Ti.mjs";const M=e=>async t=>e(t.get("lunora"),t.req.raw),F=()=>{const e=new _;return e.use("*",async(t,r)=>{const n=t.env.__lunoraCtx;if(!n)throw new p("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");t.set("lunora",n),await r()}),e},N=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,t)=>{switch(e){case"bigint":try{return BigInt(t)}catch{return t}case"boolean":return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:t;case"number":return t===""?Number.NaN:Number(t);default:return t}},P=(e,t,r)=>{const n=N(e);if(n.kind==="array"){const c=t.req.queries(r);if(c===void 0)return;const o=n._meta?.inner;return c.map(s=>g(o?.kind??"string",s))}const a=t.req.query(r);return a===void 0?void 0:g(n.kind,a)},T=(e,t)=>{const r={};for(const n of Object.keys(e)){const a=e[n];a&&(r[n]=P(a,t,n))}return R(e,r,"searchParams")},v=(e,t)=>{const r=t.req.param(),n={};for(const a of Object.keys(e)){const c=e[a];if(!c)continue;const o=r[a];n[a]=o===void 0?void 0:g(N(c).kind,o)}return R(e,n,"params")},A=async(e,t)=>{let r;try{r=await t.req.json()}catch{throw new p("BAD_REQUEST","Invalid JSON body")}if(typeof r!="object"||r===null||Array.isArray(r))throw new p("BAD_REQUEST","Expected a JSON object body");return R(e,r,"body")},x=(e,t)=>{try{return e.parse(t)}catch(r){throw r instanceof k?new p("INTERNAL_SERVER_ERROR",`Response did not match the declared output schema: ${r.message}`):r}},O=e=>{if(e instanceof k)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(e instanceof p){const{body:t,redacted:r,status:n}=S(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return r&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:t.code,error:t.message},{status:n})}throw e},q=(e,t)=>async r=>{try{const n=r.get("lunora"),a=Object.keys(e.searchParams).length>0?T(e.searchParams,r):{},c=Object.keys(e.params).length>0?v(e.params,r):{},o=Object.keys(e.body).length>0?await A(e.body,r):{},s=await t({body:o,ctx:n,params:c,searchParams:a}),u=e.output?x(e.output,s):s,i={};e.cacheControl&&(i["cache-control"]=e.cacheControl),e.cacheTag&&(i["cache-tag"]=e.cacheTag),e.vary&&(i.vary=e.vary);const f=Object.keys(i).length>0;return u===void 0?new Response(null,{headers:f?i:void 0,status:204}):Response.json(u,{headers:f?i:void 0})}catch(n){return O(n)}},E={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,t)=>{const r=JSON.stringify(e);return`${t?`event: ${t}
|
|
2
|
+
`:""}data: ${r}
|
|
3
|
+
|
|
4
|
+
`},C=(e,t)=>(async r=>{let n,a;try{n=Object.keys(e.searchParams).length>0?T(e.searchParams,r):{},a=Object.keys(e.params).length>0?v(e.params,r):{}}catch(h){return O(h)}const c=r.get("lunora"),o=r.req.raw,s=new TextEncoder,u=new AbortController;if(o.signal.aborted)return u.abort(),new Response("",{headers:E});const i=()=>{u.abort()};o.signal.addEventListener("abort",i,{once:!0});const f=new ReadableStream({cancel(){o.signal.removeEventListener("abort",i),u.abort()},async start(h){try{const m=t({ctx:c,params:a,request:o,searchParams:n,signal:u.signal});for await(const y of m){if(u.signal.aborted)break;h.enqueue(s.encode(b(y)))}h.enqueue(s.encode(b({},"complete")))}catch(m){const{body:y,redacted:j}=S(m,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});j&&console.error("[lunora] unhandled stream handler error:",m),h.enqueue(s.encode(b({code:y.code,message:y.message},"error")))}finally{o.signal.removeEventListener("abort",i),h.close()}}});return new Response(f,{headers:E})}),d=e=>({body:t=>d({...e,body:{...e.body,...t}}),cacheControl:t=>d({...e,cacheControl:t}),cacheTag:t=>d({...e,cacheTag:t}),handler:t=>q(e,t),output:t=>d({...e,output:t}),params:t=>d({...e,params:{...e.params,...t}}),searchParams:t=>d({...e,searchParams:{...e.searchParams,...t}}),stream:t=>C(e,t),vary:t=>d({...e,vary:t})}),l=e=>t=>d({body:{},method:e,params:{},path:t,searchParams:{}}),U={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},H=/^bytes=(\d*)-(\d*)$/,w=e=>e.startsWith('"')||e.startsWith('W/"')?e:`"${e}"`,$=e=>!(e.includes("\r")||e.includes(`
|
|
5
|
+
`)||e.includes("\0")),B=(e,t)=>{if(e===null)return{kind:"full"};const r=H.exec(e.trim());if(!r)return{kind:"full"};const n=r[1]??"",a=r[2]??"";if(n===""&&a==="")return{kind:"full"};let c,o;if(n===""){const s=Number(a);if(s===0)return{kind:"unsatisfiable"};c=Math.max(0,t-s),o=t-1}else c=Number(n),o=a===""?t-1:Math.min(Number(a),t-1);return c>o||c>=t?{kind:"unsatisfiable"}:{end:o,kind:"partial",start:c}},W=async(e,t,r)=>{const n=await e.storage.download(t);if(!n)return new Response("Not Found",{status:404});const a=n.httpMetadata?.contentType,o={"accept-ranges":"bytes","content-type":a!==void 0&&$(a)?a:"application/octet-stream",etag:w(n.etag)};n.sha256Base64!==void 0&&(o["repr-digest"]=`sha-256=:${n.sha256Base64}:`);const s=B(r.headers.get("range"),n.size);if(s.kind==="unsatisfiable")return n.body?.cancel().catch(()=>{}),new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(n.size)}`,"content-type":"text/plain; charset=utf-8",etag:w(n.etag)},status:416});if(s.kind==="full")return new Response(n.body,{headers:{...o,"content-length":String(n.size)},status:200});n.body?.cancel().catch(()=>{});const u=s.end-s.start+1,i=await e.storage.download(t,{range:{length:u,offset:s.start}});return i?new Response(i.body,{headers:{...o,"content-length":String(u),"content-range":`bytes ${String(s.start)}-${String(s.end)}/${String(n.size)}`},status:206}):new Response("Not Found",{status:404})};export{M as httpAction,U as httpRoute,F as httpRouter,$ as isSafeHeaderValue,W as serveStorageObject};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{v as f}from"./functions-B2-H4PQT.mjs";import{readMaskTag as M}from"./buildMaskRegistry-72SL8fJn.mjs";import{r as h}from"./policy-tag-D4RzgQnw.mjs";import{r as j}from"./run-middleware-B-JeGGp9.mjs";const x=(e,r)=>r===void 0||typeof e!="object"||e===null?e:Object.assign(Object.create(Object.getPrototypeOf(e)),e,{meta:r}),i=(e,r)=>j(e,r,o=>o),_=(e,r,o,a,n)=>async(s,u)=>{const c=f(e,u),t=await i(r,x(s,n)),l=await o({args:c,ctx:t});return a?a.parse(l):l},q=(e,r,o,a)=>(n,s,u)=>{const c=f(e,s);return(async function*(){const l=await i(r,x(n,a)),m=o({args:c,ctx:l,signal:u})[Symbol.asyncIterator]();try{for(;;){if(u.aborted)return;const w=await m.next();if(w.done||u.aborted)return;yield w.value}}finally{await m.return?.()}})()},g=e=>{const r=e.map(o=>h(o)).filter(o=>o!==void 0);return r.length>0?{tags:r}:void 0},p=e=>{const r=new Map;for(const o of e){const a=M(o);if(a)for(const[n,s]of a.columns){const u=r.get(n)??new Set;for(const c of s)u.add(c);r.set(n,u)}}return r.size>0?r:void 0},d=(e,r,o)=>({__lunoraProcedure:e,...o?{__lunoraVisibility:o}:{},input:a=>d(e,{...r,args:{...r.args,...a}},o),[e]:a=>{const n=g(r.middlewares),s=p(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:_(r.args,r.middlewares,a,r.output,r.meta),kind:e,...s?{maskedTables:s}:{},...r.meta?{meta:r.meta}:{},...n?{rls:n}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}},meta:a=>d(e,{...r,meta:Object.freeze({...r.meta,...a})},o),output:a=>d(e,{...r,output:a},o),...e==="query"?{stream:(a,n)=>{const s=g(r.middlewares),u=p(r.middlewares),c=n?.durable===!0?{}:n?.durable;return{args:r.args,...c?{durable:c}:{},...r.expose?{expose:r.expose}:{},handler:q(r.args,r.middlewares,a,r.meta),kind:"stream",...u?{maskedTables:u}:{},...r.meta?{meta:r.meta}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}}}:{},use:a=>d(e,{...r,middlewares:[...r.middlewares,a]},o),...o?{}:{expose:a=>d(e,{...r,expose:a},o)},...o?{}:{x402:a=>d(e,{...r,x402:a},o)}}),y={dataModel:()=>({create:e=>({action:d("action",{args:{},middlewares:[]}),internalAction:d("action",{args:{},middlewares:[]},"internal"),internalMutation:d("mutation",{args:{},middlewares:[]},"internal"),internalQuery:d("query",{args:{},middlewares:[]},"internal"),mutation:d("mutation",{args:{},middlewares:[]}),query:d("query",{args:{},middlewares:[]})})})};export{y as initLunora};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as P}from"./LunoraError-DcKdk9Ti.mjs";import{bindTableFacade as j,bindOrm as E}from"./bindOrm-lWdeDi9P.mjs";import{i as _,a as D,o as v,b as K}from"./middleware-DEW0yLvU.mjs";import{tagMaskMiddleware as q}from"./buildMaskRegistry-72SL8fJn.mjs";const G=e=>{let i=2166136261;for(let c=0;c<e.length;c+=1)i^=e.codePointAt(c)??0,i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},L=(e,i,c)=>{try{return e==="redact"?null:e==="hash"?i==null?i:G(typeof i=="string"?i:JSON.stringify(i)):e(i,c)}catch{return null}},a=(e,i,c)=>{const y={...e};for(const[h,g]of Object.entries(i))h in y&&(y[h]=L(g,e[h],{...c,column:h,row:e}));return y},W=(e,i,c)=>({...e,page:e.page.map(y=>a(y,i,c))}),B=(e,i,c,y)=>{if(typeof e!="function")return;const h=new Set,g=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&h.add(f),g())});e(g());for(const f of h)if(f in i)throw new P("MASK_UNSUPPORTED",`${y}() filtering "${c}" by masked column "${f}" is not supported`)},m=(e,i,c,y)=>{const h=e.rankBefore,g=e.rankPageRows,f=(r,n)=>{const t=i.get(r);return t?n.map(o=>a(o,t,c)):n},p=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?f:(t,o)=>n(t,f(t,o))}},k=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const d=y?.[r]?.[o]?.[n];if(!d)return;const w=d.find($=>$ in s);if(w!==void 0)throw new P("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${w}" — use an index whose declared fields are all unmasked, or unmask the column`)},l=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield a(o,n,c)},collect:async()=>(await r.collect()).map(s=>a(s,n,c)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const d=a(s.document,n,c);return"distanceMeters"in s?{distanceMeters:null,document:d}:{document:d,score:s.score}}),filter:o=>l(r.filter(s=>o(a(s,n,c))),n,t),first:async()=>{const o=await r.first();return o?a(o,n,c):null},order:o=>l(r.order(o),n,t),paginate:async o=>W(await r.paginate(o),n,c),take:async o=>(await r.take(o)).map(d=>a(d,n,c)),unique:async()=>{const o=await r.unique();return o?a(o,n,c):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),B(s,n,t,"withIndex"),l(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(B(s,n,t,"withSearchIndex"),l(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),l(r.withGeoIndex(o,s),n,t))}),S=async(r,n)=>{if(e.lookupById){const w=await e.lookupById(r,n);return w?{row:w.row,tableName:i.has(w.tableName)?w.tableName:void 0}:{row:null,tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,d=await Promise.all(s.map(async w=>(await e.findFirst(w,{limit:1,where:{_id:r}}))?._id===r?w:void 0));return{row:t,tableName:d.find(w=>w!==void 0)}},M=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(d=>typeof d=="string"&&d in o);if(s!==void 0)throw new P("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},R=(r,n)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[t,o]of Object.entries(r))if(t==="AND"||t==="OR"){if(Array.isArray(o))for(const s of o)R(s,n)}else t==="NOT"?R(o,n):t.startsWith("__")||n.add(t)},u=(r,n,t)=>{const o=i.get(r);if(!o||n===void 0)return;const s=new Set;R(n,s);for(const d of s)if(d in o)throw new P("MASK_UNSUPPORTED",`${t}() filtering "${r}" by masked column "${d}" is not supported`)},I=(r,n,t)=>{const o=i.get(r);if(!(!o||!Array.isArray(n))){for(const s of n)if(s&&typeof s=="object"&&!Array.isArray(s)){for(const d of Object.keys(s))if(d in o)throw new P("MASK_UNSUPPORTED",`${t}() ordering "${r}" by masked column "${d}" is not supported`)}}},F=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,A=(r,n,t)=>{const o=F(n);u(r,o?.where,t),u(r,o?.baseWhere,t)},O={...e,async deleteWhere(r,n,t){if(u(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new P("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(u(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new P("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return M(r,[n.field],"aggregate"),u(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=F(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return u(r,o,"count"),t&&u(r,t.baseWhere,"count"),e.count(r,n)},async findFirst(r,n){u(r,n?.where,"findFirst"),u(r,n?.baseWhere,"findFirst"),I(r,n?.orderBy,"findFirst");const t=await e.findFirst(r,p(n)),o=i.get(r);return t&&o?a(t,o,c):t},async findFirstOrThrow(r,n){u(r,n?.where,"findFirstOrThrow"),u(r,n?.baseWhere,"findFirstOrThrow"),I(r,n?.orderBy,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,p(n)),o=i.get(r);return o?a(t,o,c):t},async findMany(r,n){u(r,n?.where,"findMany"),u(r,n?.baseWhere,"findMany"),I(r,n?.orderBy,"findMany");const t=await e.findMany(r,p(n)),o=i.get(r);return o?W(t,o,c):t},async get(r,n){const{row:t,tableName:o}=await S(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:a(t,s,c)},async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?a(t.row,o,c):t.row,tableName:t.tableName}},groupBy(r,n){return M(r,[...n.by,n.agg?.field],"groupBy"),u(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?l(n,t,r):n},async rank(r,n,t){return A(r,t,"rank"),k(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){A(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?W(o,s,c):o},...v("rankBefore",h,r=>(n,t,o)=>(A(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),...v("rankPageRows",g,r=>async(n,t,o)=>{A(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),d=i.get(n);return d?{...s,rows:s.rows.map(w=>({...w,doc:a(w.doc,d,c)}))}:s})},U=O;for(const r of i.keys())K(e[r])&&(U[r]=j(O,r));return O},Q=(e,i={})=>{const c=new Map(Object.entries(e)),y=_(i.roles),h=async({ctx:f,next:p})=>{const k={auth:await D(f.auth??{},y),ctx:f};if(i.bypass?.(k))return p();const l=m(f.db,c,k,i.indexFields),S={db:l},{orm:M}=f;return M!==null&&typeof M=="object"&&(S.orm=E(l)),p({ctx:S})},g=new Map;for(const[f,p]of c)g.set(f,new Set(Object.keys(p)));return q(h,{columns:g})};export{Q as mask};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as W}from"./LunoraError-DcKdk9Ti.mjs";import{bindTableFacade as L,bindOrm as j}from"./bindOrm-lWdeDi9P.mjs";import{t as T}from"./policy-tag-D4RzgQnw.mjs";import{deny as $}from"./allowAll-DkRAgItV.mjs";const I=(r,t,i)=>t?{[r]:i(t)}:{},D=500,B=(r,t,i)=>{const a=t??D;if(r>a)throw new W("BAD_REQUEST",`${i}: batch of ${String(r)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`)},q=$(),N=Symbol.for("lunora.ctxdb.rls-unwrap"),K=r=>{const t=new Map;for(const i of r){const a=t.get(i.table)??[];a.push(i),t.set(i.table,a)}return t},Y=(r,t)=>{const i=[];let a=!1;for(const h of r){if(h.on!=="read")continue;const f=h.when(t);if(f!==void 0){if(f===!0){a=!0;break}f!==!1&&i.push(f)}}if(!a)return i.length===0?q:i.length===1?i[0]:{OR:i}},E=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),z=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],p=r=>{const t=typeof r;return t==="number"||t==="string"||t==="bigint"},Q=(r,t)=>!("lt"in t&&(!p(r)||!p(t.lt)||r>=t.lt)||"lte"in t&&(!p(r)||!p(t.lte)||r>t.lte)||"gt"in t&&(!p(r)||!p(t.gt)||r<=t.gt)||"gte"in t&&(!p(r)||!p(t.gte)||r<t.gte)),G=(r,t)=>{if("in"in t){const i=t.in;if(!Array.isArray(i)||!i.includes(r))return!1}if("notIn"in t){const i=t.notIn;if(Array.isArray(i)&&i.includes(r))return!1}if("contains"in t){const i=t.contains;if(typeof r!="string"||typeof i!="string"||!r.includes(i))return!1}return!("isNull"in t&&t.isNull===!0!==(r==null))},H=(r,t)=>"eq"in t&&r!==t.eq||"ne"in t&&r===t.ne?!1:G(r,t)&&Q(r,t),J=(r,t,i,a)=>t==="AND"?Array.isArray(i)&&i.every(h=>a(r,h)):t==="OR"?Array.isArray(i)&&i.some(h=>a(r,h)):!a(r,i??{}),C=r=>r==="AND"||r==="OR"||r==="NOT",X=r=>E(r)&&Object.keys(r).every(t=>z.includes(t)),Z=["every","is","isNot","none","some"],x=r=>E(r)&&Object.keys(r).length>0&&Object.keys(r).every(t=>Z.includes(t)),P=r=>Object.keys(r).some(t=>{const i=r[t];return C(t)?t==="NOT"?P(i??{}):Array.isArray(i)&&i.some(a=>P(a??{})):x(i)}),A=(r,t)=>{for(const i of Object.keys(t)){const a=t[i];if(C(i)){if(!J(r,i,a,A))return!1;continue}const h=r[i];if(X(a)){if(!H(h,a))return!1;continue}if(h!==a)return!1}return!0},V=(r,t,i)=>{const a=r.when({...t,row:i});if(a===void 0||a===!0)return!0;if(a===!1)return!1;if(P(a))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return A(i,a)},ee=(r,t,i)=>{const a=r.when(t);if(a===void 0||a===!0)return i===void 0||V(r,t,i);if(a===!1)return!1;if(P(a))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!A(t.row,a)?!1:i===void 0||A(i,a)},_=(r,t,i,a)=>{let h=!1;for(const f of r)if(f.on===t&&(h=!0,!ee(f,i,a)))return!1;return h},re=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),te=(r,t)=>t===void 0?!0:r==="restrictsCounts"?typeof t=="boolean":r==="relationBaseWhere"?typeof t=="function":E(t),ne=r=>{const t=Object.keys(r);return t.length===0?!1:t.every(i=>re.has(i)&&te(i,r[i]))},se=r=>r===void 0?{}:E(r)&&ne(r)?r:{where:r},w=(r,t)=>!t||Object.keys(t).length===0?r:!r||Object.keys(r).length===0?t:{AND:[t,r]},ie=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return!1;const t=r;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},oe=(r,t,i,a)=>{const h=new Map,f=e=>{const n=h.get(e);if(n)return n;const s=i.get(e);if(!s||s.length===0||!s.some(l=>l.on==="read")){const l={baseWhere:void 0,restricts:!1};return h.set(e,l),l}const c={baseWhere:Y(s,a),restricts:!0};return h.set(e,c),c},d=e=>f(e).restricts?t:r,y=e=>f(e).baseWhere,O=async(e,n)=>{if(t.lookupById){const u=await t.lookupById(e,n);return u?{row:u.row,tableName:i.has(u.tableName)?u.tableName:void 0}:{row:null,tableName:void 0}}const s=await t.get(e,n);if(!s)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],c=n===void 0?[...i.keys()]:o,l=await Promise.all(c.map(async u=>(await t.findFirst(u,{limit:1,where:{_id:e}}))?._id===e?u:void 0));return{row:s,tableName:l.find(u=>u!==void 0)}},M=async(e,n)=>{const s=await O(e,n);return s.row&&s.tableName!==void 0?{row:s.row,tableName:s.tableName}:void 0},g=async(e,n,s,o,c)=>{const l=await M(e,c);if(!l)return s(r);const u=i.get(l.tableName);if(u){const k=o?o(l.row):void 0;if(!_(u,n,{...a,row:l.row},k))throw new W("FORBIDDEN",`${n} denied by policy`)}return s(t)},b=(e,n)=>{const{baseWhere:s,restricts:o}=f(e);if(o)throw new W("COUNT_RLS_UNSUPPORTED",`${n}() is not supported on "${e}" inside an RLS-restricted context`);return s},v=r.rankBefore,U=r.rankPageRows,R={...r,async count(e,n){const{baseWhere:s,restricts:o}=f(e),c=se(n);return d(e).count(e,{...c,baseWhere:w(c.baseWhere,s),relationBaseWhere:y,restrictsCounts:(c.restrictsCounts??!1)||o})},delete:(e,n,s)=>g(e,"delete",o=>o.delete(e,n,s),void 0,n),async deleteAll(e,n){const s=Math.max(1,n?.chunkSize??D),{baseWhere:o}=f(e);let c=0;for(;;){const u=(await d(e).findMany(e,{baseWhere:o,limit:s,relationBaseWhere:y})).page.map(k=>String(k._id));if(u.length===0)break;for(const k of u)await g(k,"delete",S=>S.delete(k,void 0,n?.hard===void 0?void 0:{hard:n.hard})),c+=1;if(u.length<s)break}return{deleted:c}},async deleteMany(e,n,s){B(e.length,n?.limit,"deleteMany");for(const o of e)await g(o,"delete",c=>c.delete(o,s),void 0,s);return{deleted:e.length}},async deleteWhere(e,n,s){const{baseWhere:o}=f(e),l=(await d(e).findMany(e,{baseWhere:w(n,o),relationBaseWhere:y})).page.map(u=>String(u._id));return B(l.length,s?.limit,"deleteWhere"),R.deleteMany(l,s)},async findFirst(e,n){const{baseWhere:s}=f(e);return d(e).findFirst(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async findFirstOrThrow(e,n){const{baseWhere:s}=f(e);return d(e).findFirstOrThrow(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async findMany(e,n){const{baseWhere:s}=f(e);return d(e).findMany(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async get(e,n){const s=await O(e,n);if(!s.row)return null;if(s.tableName===void 0)return r.get(e,n);const{baseWhere:o,restricts:c}=f(s.tableName);if(!c)return r.get(e,n);if(!o)return s.row;const l=await t.findFirst(s.tableName,{baseWhere:o,limit:1,where:{_id:e}});return l?._id===e?l:null},async lookupById(e,n){const s=await O(e,n);if(!s.row)return null;if(s.tableName===void 0||!f(s.tableName).restricts)return await r.lookupById?.(e,n)??null;const{baseWhere:o}=f(s.tableName);if(!o)return{row:s.row,tableName:s.tableName};const c=await t.findFirst(s.tableName,{baseWhere:o,limit:1,where:{_id:e}});return c?._id===e?{row:c,tableName:s.tableName}:null},async insert(e,n){const s=i.get(e);if(s){if(!_(s,"insert",{...a,row:n}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insert(e,n)}return r.insert(e,n)},async insertMany(e,n,s){B(n.length,s?.limit,"insertMany");const o=i.get(e);if(o){for(const c of n)if(!_(o,"insert",{...a,row:c}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertMany(e,n,s)}return r.insertMany(e,n,s)},async insertManyUnsafe(e,n,s){B(n.length,s?.limit,"insertManyUnsafe");const o=i.get(e);if(o){for(const c of n)if(!_(o,"insert",{...a,row:c}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertManyUnsafe(e,n,s)}return r.insertManyUnsafe(e,n,s)},patch:(e,n,s)=>g(e,"update",o=>o.patch(e,n,s),o=>({...o,...n}),s),async patchMany(e,n,s){B(e.length,n?.limit,"patchMany");for(const o of e)await g(o.id,"update",c=>c.patch(o.id,o.patch,s),c=>({...c,...o.patch}),s);return{patched:e.length}},async patchWhere(e,n,s){const{baseWhere:o}=f(e),l=(await d(e).findMany(e,{baseWhere:w(n.where,o),relationBaseWhere:y})).page.map(u=>({id:String(u._id),patch:n.patch}));return B(l.length,s?.limit,"patchWhere"),R.patchMany(l,s)},query(e){const{baseWhere:n}=f(e),s=d(e).query(e);return n?s.filter(o=>A(o,n)):s},restore:(e,n)=>g(e,"update",async s=>{const o=s.restore??t.restore;if(!o)throw new W("BAD_REQUEST","restore is not supported by this writer");await o(e,n)},void 0,n),replace:(e,n,s)=>g(e,"update",o=>o.replace(e,n,s),o=>({...n,_creationTime:n._creationTime??o._creationTime,_id:o._id}),s),aggregate(e,n){const{baseWhere:s}=f(e);return d(e).aggregate(e,{...n,baseWhere:w(n.baseWhere,s),relationBaseWhere:y})},groupBy(e,n){const{baseWhere:s}=f(e);return d(e).groupBy(e,{...n,baseWhere:w(n.baseWhere,s),relationBaseWhere:y})},rank(e,n,s){const o=b(e,"rank");return d(e).rank(e,n,{...s,baseWhere:w(s.baseWhere,o)})},rankPage(e,n,s){const o=b(e,"rankPage");return d(e).rankPage(e,n,{...s,baseWhere:w(s?.baseWhere,o)})},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...I("rankBefore",v,e=>(n,s,o)=>(b(n,"rankBefore"),(d(n).rankBefore??e)(n,s,o))),...I("rankPageRows",U,e=>(n,s,o)=>{const c=b(n,"rankPageRows");return(d(n).rankPageRows??e)(n,s,{...o,baseWhere:w(o?.baseWhere,c)})})},m=R;for(const e of i.keys())ie(r[e])&&(m[e]=L(R,e));return R},F=r=>typeof r=="string"?r:r.name,ae=r=>{const t=new Map;for(const i of r??[])t.set(i.name,new Set((i.permissions??[]).map(a=>F(a))));return t},ce=(r,t)=>{const i=new Set;for(const a of r)for(const h of t.get(a)??[])i.add(h);return a=>i.has(F(a))},fe=async(r,t)=>{const i=r.roles??[];return{can:ce(i,t),identity:await r.getIdentity?.()??null,roles:i,userId:r.userId??null}},ye=(r,t={})=>{const i=K(r),a=ae(t.roles);return T(async({ctx:f,next:d})=>{const y={auth:await fe(f.auth??{},a),ctx:f},O=f.db,M=O[N]??O,g=oe(O,M,i,y),b={db:g},{orm:v}=f;return v!==null&&typeof v=="object"&&(b.orm=j(g)),d({ctx:b})},{policies:r,roles:t.roles??[]})};export{fe as a,ie as b,Y as c,ce as d,_ as e,ae as i,A as m,I as o,F as p,ye as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=(n,c)=>({args:{},handler:(i,o)=>c(i,o),kind:"mutation",lifecycle:n,visibility:"internal"}),e=n=>t("connect",n),r=n=>t("disconnect",n),s=n=>t("init",n);export{e as onConnect,r as onDisconnect,s as onShardInit};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const c=(t,e)=>{let r=e;for(let i=0;i<t.length;i+=1)r^=t.codePointAt(i)??0,r=Math.imul(r,16777619)>>>0;return r.toString(16).padStart(8,"0")},f=t=>`${c(t,2166136261)}${c(t,16777619)}`,y=(t,e)=>t<e?-1:t>e?1:0,s=t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(n=>s(n)).join(",")}]`;const e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){const n=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const r=t,i=Object.keys(r).toSorted(y),o=[];for(const n of i){const a=r[n];a!==void 0&&o.push(`${JSON.stringify(n)}:${s(a)}`)}return`{${o.join(",")}}`},p=(t,e)=>({args:{},handler:async(r,i)=>{const o=await t(r),n=f(s(o));return n===i?.previousDigest?{digest:n,ran:!1}:(await e(r,o),{digest:n,ran:!0})},kind:"mutation",lifecycle:"reactor",visibility:"internal"});export{p as onQueryChange};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{r as P}from"./run-middleware-B-JeGGp9.mjs";import{v as O}from"@lunora/values";const j=["de","en","es","fr","it","nl","none","pt"],F=["native","portable"],K=e=>F.includes(e),z=e=>j.includes(e),B=16,H={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),Q=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),_=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},se=e=>{const t={...e},n=[],r=[],o=[],d=[],u={},l=[],f={},m=Q(),b=[];let y={kind:"root"},$=!1,N=!1,k=!1,T=!1,L,M,A,R;const c={aggregateIndex(i,a){const h=a?.op??"count";if(h!=="count"&&!a?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${h}" requires a "field"`);return n.push({by:a?.by,field:a?.field,name:i,on:"",op:h,where:a?.where}),c},get aggregateIndexes(){return n},get externalSource(){return R},commitOrdered(){return $=!0,c},get commitOrderedMode(){return $},externallyManaged(){return N=!0,c},geoIndex(i,a){return r.push({field:a.field,name:i,precision:a.precision}),c},get geoIndexes(){return r},global(i){return y={backend:i?.backend??"d1",kind:"global"},c},get isExternallyManaged(){return N},get isPublic(){return T},index(i,a,h){return o.push({fields:a,name:i,unique:h?.unique??!1}),c},get indexes(){return o},memory(){return k=!0,c},get memoryMode(){return k},ownedBy(i){return L=i,c},get ownerField(){return L},public(){return T=!0,c},rankIndex(i,a){return d.push({name:i,on:"",partitionBy:a.partitionBy,sortBy:_(i,a.sortBy),where:a.where}),c},get rankIndexes(){return d},get relationMap(){return u},relations(i){return Object.assign(u,i(H)),c},searchIndex(i,a){if(a.filterFields&&a.filterFields.length>B)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(B)} filterFields are supported (got ${String(a.filterFields.length)})`);const{language:h}=a;if(h!==void 0&&!z(h))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${h}" (supported: ${j.join(", ")})`);const{strategy:v}=a;if(v!==void 0&&!K(v))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${v}" (supported: ${F.join(", ")})`);return l.push({field:a.field,filterFields:a.filterFields,language:a.language,name:i,staged:a.staged,strategy:a.strategy}),c},get searchIndexes(){return l},shape:t,shardBy(i){return y={field:i,kind:"shardBy"},c},get shardMode(){return y},get softDeleteMode(){return M},source(i){if(!i.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!i.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return R=i,N=!0,c},softDelete(i){const a=i?.field??"deletedAt";return M={field:a},a in t||(t[a]=O.optional(O.number().nullable())),c},get triggerMap(){return f},triggers(i){return Object.assign(f,i(m)),c},ttl(i,a){return A={after:a?.after,field:i},c},get ttlPolicy(){return A},get vectorIndexes(){return b},vectorize(i,a){return b.push({dimensions:a.dimensions,embed:a.embed,field:i,metadata:a.metadata,metric:a.metric,name:a.index}),c}};return c},de=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),le=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},ce=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:_(e,t.sortBy),where:t.where}),x=e=>({...e,extend(t){return x(C(e,t))},jurisdiction(t){return x(e)},rls(t){return x({...e,rlsMode:t})}}),X=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},U=(e,t,n)=>{for(const r of Object.values(t)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);o.aggregateIndexes.push(r)}for(const r of Object.values(n)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);o.rankIndexes.push(r)}},V=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},Y=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=V(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},J=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);Y(t,r)}}},W=["_commitSeq","_creationTime","_id"],D="_commitSeq",G=new Set(W),w=(e,t,n,r)=>{if(!(G.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},p=(e,t,n,r)=>{const o=new Set;for(const d of n){if(o.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);o.add(d.name),r(d)}},q=e=>{for(const[t,n]of Object.entries(e))p(t,"index",n.indexes,r=>{for(const o of r.fields)w(t,r.name,o,n)}),p(t,"rank index",n.rankIndexes,r=>{for(const o of r.sortBy)w(t,r.name,o.field,n);for(const o of r.partitionBy??[])w(t,r.name,o,n)}),p(t,"geo index",n.geoIndexes,r=>{w(t,r.name,r.field,n)})},E=(e,t,n)=>{if(e.length===0)return;const r={};for(const o of e)r[t(o)]=n(o);return r},Z=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},ue=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const o=E(r.geoIndexes,l=>l.name,l=>[l.field]),d=E(r.indexes,l=>l.name,l=>l.fields),u=E(r.rankIndexes,l=>l.name,Z);(o||d||u)&&(t[n]={...o?{geo:o}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ee=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const o=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(o!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${o}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},te=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(D))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${D}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},fe=(e,t={},n={},r={})=>(X(e),U(e,n,r),J(e),te(e),ee(e),q(e),x({tables:e,vectorIndexes:t})),I=(e,t)=>`${e}_${t}`,S=(e,t,n)=>n.has(e)?I(t,e):e,ne=(e,t,n,r)=>{const o=I(t,r),d=m=>m===""?o:S(m,t,n),u={};for(const[m,b]of Object.entries(e.relationMap))u[m]={...b,table:S(b.table,t,n)};const l=e.aggregateIndexes.map(m=>({...m,on:d(m.on)})),f=e.rankIndexes.map(m=>({...m,on:d(m.on)}));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:u}},me=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},re=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),he=(e,t)=>({...re(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),C=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),o={...e.tables};for(const[u,l]of Object.entries(t.tables)){const f=I(n,u);if(Object.hasOwn(o,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);o[f]=ne(l,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,l]of Object.entries(t.vectorIndexes)){const f=I(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...l,table:S(l.table,n,r)}}return q(o),{rlsMode:e.rlsMode,tables:o,vectorIndexes:d}},ge=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=C(n,r.extension));return n},be=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return(async({ctx:n,next:r})=>P(t,n,o=>r({ctx:o})))};export{he as a,re as b,be as c,le as d,ce as e,fe as f,me as g,se as h,de as i,ue as j,ge as k,C as m,q as v};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=Symbol.for("lunora.rls.middleware-policies"),r=(e,o)=>(Object.defineProperty(e,t,{configurable:!0,enumerable:!1,value:o}),e),n=e=>{if(!(e===null||typeof e!="function"&&typeof e!="object"))return e[t]};export{n as r,r as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as o}from"./run-middleware-B-JeGGp9.mjs";const s=c=>{const t=[c.rateLimit,c.captcha,...c.use??[]].filter(r=>r!==void 0);return async({ctx:r,next:e})=>o(t,r,a=>e({ctx:a}))};export{s as protectPublic};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./LunoraError-DcKdk9Ti.mjs";import"./bindOrm-lWdeDi9P.mjs";import{c as m,e as t,i as p,b as l,m as c,p as n,d,a as h,r as u}from"./middleware-DEW0yLvU.mjs";import"./policy-tag-D4RzgQnw.mjs";import"./allowAll-DkRAgItV.mjs";export{m as computeReadBaseWhere,t as evaluateWrite,p as indexRolePermissions,l as isFacadeEntry,c as matchesWhere,n as permissionName,d as resolveCan,h as resolvePolicyAuth,u as rls};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as o}from"@lunora/errors";const m=async(l,c,i)=>{let t=-1;const e=async(r,a)=>{if(r<=t)throw new o("INTERNAL","middleware next() called multiple times");t=r;const n=l[r];return n?await n({ctx:a,next:(s=>e(r+1,s?.ctx?{...a,...s.ctx}:a))}):i(a)};return e(0,c)};export{m as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"./LunoraError-DcKdk9Ti.mjs";import{i as U,a as v}from"./middleware-DEW0yLvU.mjs";const D=(o,e)=>o===void 0||e.startsWith(o),k=o=>{const e=o[1],c=typeof e=="object"&&e!==null?e.method:void 0;return typeof c=="string"&&c.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",k],["getUrl","read"],["store","write"]],S=(o,e={})=>{const c=U(e.roles);return async({ctx:u,next:f})=>{const h=await v(u.auth??{},c),g=(n,r,s)=>{const a=o.filter(t=>t.on===n&&t.bucket===s);if(a.length===0)return;const i={auth:h,ctx:u,key:r};if(!a.some(t=>D(t.prefix,r)&&t.when(i)===!0))throw new y("FORBIDDEN",`storage ${n} on "${r}" in bucket "${s}" denied by access rule`)},p=n=>{const r=n.bucketName??"default",s={bucketName:r};for(const[i,l]of E){const t=n[i];typeof t=="function"&&(s[i]=(...d)=>{const m=typeof d[0]=="string"?d[0]:"",b=typeof l=="function"?l(d):l;return g(b,m,r),t(...d)})}const{bucket:a}=n;return typeof a=="function"&&(s.bucket=i=>p(a(i))),s},w=u.storage;return w===void 0?f():f({ctx:{storage:p(w)}})}};export{S as storageRules};
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { WhereOf } from "../data-model.mjs";
|
|
2
|
+
/** Structural mirror of `@lunora/do`'s `WhereInput`. */
|
|
3
|
+
interface WhereInput {
|
|
4
|
+
[field: string]: unknown;
|
|
5
|
+
AND?: WhereInput[];
|
|
6
|
+
NOT?: WhereInput;
|
|
7
|
+
OR?: WhereInput[];
|
|
8
|
+
}
|
|
9
|
+
/** Operations a policy can gate. `read` covers `get`/`findMany`/`query`/`count`. */
|
|
10
|
+
type PolicyOperation = "delete" | "insert" | "read" | "update";
|
|
11
|
+
/**
|
|
12
|
+
* A policy's `when` decision:
|
|
13
|
+
*
|
|
14
|
+
* - `WhereInput`: a row-shape predicate. On reads it is AND-merged into every
|
|
15
|
+
* query against the table — the row is invisible unless it matches. On writes
|
|
16
|
+
* it is evaluated against the candidate document (`insert`) or the pre-write
|
|
17
|
+
* row (`update`/`delete`); a mismatch denies the write with
|
|
18
|
+
* `LunoraError("FORBIDDEN")`. Same operator set as the SQL compiler
|
|
19
|
+
* (`eq`/`ne`/`in`/`notIn`/`lt`/`lte`/`gt`/`gte`/`isNull`/`contains` +
|
|
20
|
+
* `AND`/`OR`/`NOT`).
|
|
21
|
+
* - `true`: unrestricted. On reads no predicate is merged; on writes the row is
|
|
22
|
+
* allowed.
|
|
23
|
+
* - `false`: deny. On reads the table is forced to match zero rows (a sentinel
|
|
24
|
+
* predicate); on writes the operation throws `LunoraError("FORBIDDEN")`.
|
|
25
|
+
*
|
|
26
|
+
* Returning `undefined` opts this specific policy out (rare; useful when
|
|
27
|
+
* branching on `ctx.auth.roles`).
|
|
28
|
+
*/
|
|
29
|
+
type PolicyDecision = WhereInput | boolean | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Relation-aware twin of {@link PolicyDecision}, parameterized over the
|
|
32
|
+
* generated `DataModel` (`DM`) + `Relations` (`REL`) maps and a table `T`. A
|
|
33
|
+
* read policy may now return a Prisma-style relation predicate (the
|
|
34
|
+
* `@lunora/do` pre-resolver resolves it via a semijoin), so the typed
|
|
35
|
+
* authoring surface accepts `WhereOf<DM, REL, T>` — column predicates **and**
|
|
36
|
+
* `is`/`isNot`/`some`/`none`/`every` over `T`'s declared relations — in
|
|
37
|
+
* addition to the `boolean`/`undefined` decisions. Used by the project-bound
|
|
38
|
+
* `definePolicy` from `createPolicyDsl`.
|
|
39
|
+
*/
|
|
40
|
+
type PolicyDecisionOf<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = WhereOf<DM, REL, T> | boolean | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Relation-aware input for a project-bound `definePolicy` (see
|
|
43
|
+
* `createPolicyDsl`). `table` is constrained to a real table name and
|
|
44
|
+
* `when`'s return type is the table-specific {@link PolicyDecisionOf} — so an
|
|
45
|
+
* unknown table, a stray column, or a relation predicate naming a relation the
|
|
46
|
+
* table does not declare is a compile error rather than a silent runtime deny.
|
|
47
|
+
*/
|
|
48
|
+
interface TypedDefinePolicyInput<DM, REL extends Record<keyof DM, object>, T extends keyof DM, Context = unknown, Identity = Record<string, unknown>> {
|
|
49
|
+
on: PolicyOperation;
|
|
50
|
+
table: T;
|
|
51
|
+
when: (context: PolicyContext<Context, Identity>) => PolicyDecisionOf<DM, REL, T>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Context handed to a policy. `auth.roles` is the per-request role list,
|
|
55
|
+
* sourced from the identity resolver (better-auth claims today). `auth.can`
|
|
56
|
+
* answers whether any of those roles grants a permission (see
|
|
57
|
+
* {@link Permission} / {@link RlsOptions}). `row` is present only on write
|
|
58
|
+
* policies (`insert`/`update`/`delete`) — for `update` and `delete` it is the
|
|
59
|
+
* pre-write row; for `insert` it is the candidate document. `ctx` is the full
|
|
60
|
+
* procedure context the middleware closed over.
|
|
61
|
+
*/
|
|
62
|
+
interface PolicyContext<Context = unknown, Identity = Record<string, unknown>> {
|
|
63
|
+
readonly auth: {
|
|
64
|
+
/**
|
|
65
|
+
* `true` when any of the request's `roles` grants `permission` (passed
|
|
66
|
+
* by {@link Permission} object or its `name`). Always `false` when no
|
|
67
|
+
* roles were handed to the middleware (`rls(policies, { roles })`), or
|
|
68
|
+
* when none of the request's roles lists the permission.
|
|
69
|
+
*/
|
|
70
|
+
readonly can: (permission: Permission | string) => boolean;
|
|
71
|
+
/**
|
|
72
|
+
* The resolved identity, typed to the `Identity` type parameter bound on
|
|
73
|
+
* `createPolicyDsl` — e.g. the app's `defineIdentity(...)` claim type via
|
|
74
|
+
* the `InferIdentity` helper; otherwise the untyped claim bag.
|
|
75
|
+
* `undefined`/`null` when the request is anonymous.
|
|
76
|
+
*/
|
|
77
|
+
readonly identity?: Identity | null;
|
|
78
|
+
readonly roles: ReadonlyArray<string>;
|
|
79
|
+
readonly userId: null | string;
|
|
80
|
+
};
|
|
81
|
+
readonly ctx: Context;
|
|
82
|
+
readonly row?: Record<string, unknown>;
|
|
83
|
+
}
|
|
84
|
+
/** A registered policy as stored in the policy table. */
|
|
85
|
+
interface Policy<Context = unknown> {
|
|
86
|
+
readonly on: PolicyOperation;
|
|
87
|
+
readonly table: string;
|
|
88
|
+
readonly when: (context: PolicyContext<Context>) => PolicyDecision;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Input accepted by `definePolicy`. The branded result is the same
|
|
92
|
+
* shape; we keep the input/output split so callers can read JSDoc on the
|
|
93
|
+
* constructor without the type re-exposing `Policy` internals.
|
|
94
|
+
*/
|
|
95
|
+
interface DefinePolicyInput<Context = unknown> {
|
|
96
|
+
on: PolicyOperation;
|
|
97
|
+
/** Logical table name the policy applies to. */
|
|
98
|
+
table: string;
|
|
99
|
+
/**
|
|
100
|
+
* Decision function. Returning a `WhereInput` (read only) AND-merges the
|
|
101
|
+
* predicate; `true` allows; `false` denies; `undefined` skips this policy.
|
|
102
|
+
*
|
|
103
|
+
* NOTE: `count()` is **unsupported** on a policy-restricted table — the
|
|
104
|
+
* reader throws `LunoraError("COUNT_RLS_UNSUPPORTED")` (422). This mirrors
|
|
105
|
+
* kitcn's documented behavior.
|
|
106
|
+
*/
|
|
107
|
+
when: (context: PolicyContext<Context>) => PolicyDecision;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* A named, abstract capability a policy can check with `ctx.auth.can(...)`,
|
|
111
|
+
* instead of branching on raw role strings. Declare one with
|
|
112
|
+
* `definePermission`; grant it to a role via {@link Role.permissions};
|
|
113
|
+
* register the roles with the middleware via {@link RlsOptions.roles}.
|
|
114
|
+
*/
|
|
115
|
+
interface Permission {
|
|
116
|
+
readonly description?: string;
|
|
117
|
+
readonly name: string;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* A role declaration. Roles are string labels attached to the request's
|
|
121
|
+
* identity (via better-auth claims today). `permissions` lists the
|
|
122
|
+
* capabilities the role grants — at request time the middleware unions the
|
|
123
|
+
* permissions of every role in `ctx.auth.roles` so a policy can ask
|
|
124
|
+
* `ctx.auth.can(permission)` rather than enumerate roles.
|
|
125
|
+
*/
|
|
126
|
+
interface Role {
|
|
127
|
+
readonly description?: string;
|
|
128
|
+
readonly name: string;
|
|
129
|
+
/** Permissions this role grants — by {@link Permission} object or bare name. */
|
|
130
|
+
readonly permissions?: ReadonlyArray<Permission | string>;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Options for the `rls(policies, options)` middleware. `roles` registers the
|
|
134
|
+
* role→permission grants that back `ctx.auth.can(...)`; a role not listed here
|
|
135
|
+
* grants no permissions (so `can` is conservative — it fails closed for
|
|
136
|
+
* unknown roles).
|
|
137
|
+
*/
|
|
138
|
+
interface RlsOptions {
|
|
139
|
+
readonly roles?: ReadonlyArray<Role>;
|
|
140
|
+
}
|
|
141
|
+
export { DefinePolicyInput as D, PolicyOperation as P, Role as R, TypedDefinePolicyInput as T, WhereInput as W, Policy as a, RlsOptions as b, Permission as c, PolicyContext as d, PolicyDecision as e, PolicyDecisionOf as f };
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { WhereOf } from "../data-model.js";
|
|
2
|
+
/** Structural mirror of `@lunora/do`'s `WhereInput`. */
|
|
3
|
+
interface WhereInput {
|
|
4
|
+
[field: string]: unknown;
|
|
5
|
+
AND?: WhereInput[];
|
|
6
|
+
NOT?: WhereInput;
|
|
7
|
+
OR?: WhereInput[];
|
|
8
|
+
}
|
|
9
|
+
/** Operations a policy can gate. `read` covers `get`/`findMany`/`query`/`count`. */
|
|
10
|
+
type PolicyOperation = "delete" | "insert" | "read" | "update";
|
|
11
|
+
/**
|
|
12
|
+
* A policy's `when` decision:
|
|
13
|
+
*
|
|
14
|
+
* - `WhereInput`: a row-shape predicate. On reads it is AND-merged into every
|
|
15
|
+
* query against the table — the row is invisible unless it matches. On writes
|
|
16
|
+
* it is evaluated against the candidate document (`insert`) or the pre-write
|
|
17
|
+
* row (`update`/`delete`); a mismatch denies the write with
|
|
18
|
+
* `LunoraError("FORBIDDEN")`. Same operator set as the SQL compiler
|
|
19
|
+
* (`eq`/`ne`/`in`/`notIn`/`lt`/`lte`/`gt`/`gte`/`isNull`/`contains` +
|
|
20
|
+
* `AND`/`OR`/`NOT`).
|
|
21
|
+
* - `true`: unrestricted. On reads no predicate is merged; on writes the row is
|
|
22
|
+
* allowed.
|
|
23
|
+
* - `false`: deny. On reads the table is forced to match zero rows (a sentinel
|
|
24
|
+
* predicate); on writes the operation throws `LunoraError("FORBIDDEN")`.
|
|
25
|
+
*
|
|
26
|
+
* Returning `undefined` opts this specific policy out (rare; useful when
|
|
27
|
+
* branching on `ctx.auth.roles`).
|
|
28
|
+
*/
|
|
29
|
+
type PolicyDecision = WhereInput | boolean | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Relation-aware twin of {@link PolicyDecision}, parameterized over the
|
|
32
|
+
* generated `DataModel` (`DM`) + `Relations` (`REL`) maps and a table `T`. A
|
|
33
|
+
* read policy may now return a Prisma-style relation predicate (the
|
|
34
|
+
* `@lunora/do` pre-resolver resolves it via a semijoin), so the typed
|
|
35
|
+
* authoring surface accepts `WhereOf<DM, REL, T>` — column predicates **and**
|
|
36
|
+
* `is`/`isNot`/`some`/`none`/`every` over `T`'s declared relations — in
|
|
37
|
+
* addition to the `boolean`/`undefined` decisions. Used by the project-bound
|
|
38
|
+
* `definePolicy` from `createPolicyDsl`.
|
|
39
|
+
*/
|
|
40
|
+
type PolicyDecisionOf<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = WhereOf<DM, REL, T> | boolean | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Relation-aware input for a project-bound `definePolicy` (see
|
|
43
|
+
* `createPolicyDsl`). `table` is constrained to a real table name and
|
|
44
|
+
* `when`'s return type is the table-specific {@link PolicyDecisionOf} — so an
|
|
45
|
+
* unknown table, a stray column, or a relation predicate naming a relation the
|
|
46
|
+
* table does not declare is a compile error rather than a silent runtime deny.
|
|
47
|
+
*/
|
|
48
|
+
interface TypedDefinePolicyInput<DM, REL extends Record<keyof DM, object>, T extends keyof DM, Context = unknown, Identity = Record<string, unknown>> {
|
|
49
|
+
on: PolicyOperation;
|
|
50
|
+
table: T;
|
|
51
|
+
when: (context: PolicyContext<Context, Identity>) => PolicyDecisionOf<DM, REL, T>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Context handed to a policy. `auth.roles` is the per-request role list,
|
|
55
|
+
* sourced from the identity resolver (better-auth claims today). `auth.can`
|
|
56
|
+
* answers whether any of those roles grants a permission (see
|
|
57
|
+
* {@link Permission} / {@link RlsOptions}). `row` is present only on write
|
|
58
|
+
* policies (`insert`/`update`/`delete`) — for `update` and `delete` it is the
|
|
59
|
+
* pre-write row; for `insert` it is the candidate document. `ctx` is the full
|
|
60
|
+
* procedure context the middleware closed over.
|
|
61
|
+
*/
|
|
62
|
+
interface PolicyContext<Context = unknown, Identity = Record<string, unknown>> {
|
|
63
|
+
readonly auth: {
|
|
64
|
+
/**
|
|
65
|
+
* `true` when any of the request's `roles` grants `permission` (passed
|
|
66
|
+
* by {@link Permission} object or its `name`). Always `false` when no
|
|
67
|
+
* roles were handed to the middleware (`rls(policies, { roles })`), or
|
|
68
|
+
* when none of the request's roles lists the permission.
|
|
69
|
+
*/
|
|
70
|
+
readonly can: (permission: Permission | string) => boolean;
|
|
71
|
+
/**
|
|
72
|
+
* The resolved identity, typed to the `Identity` type parameter bound on
|
|
73
|
+
* `createPolicyDsl` — e.g. the app's `defineIdentity(...)` claim type via
|
|
74
|
+
* the `InferIdentity` helper; otherwise the untyped claim bag.
|
|
75
|
+
* `undefined`/`null` when the request is anonymous.
|
|
76
|
+
*/
|
|
77
|
+
readonly identity?: Identity | null;
|
|
78
|
+
readonly roles: ReadonlyArray<string>;
|
|
79
|
+
readonly userId: null | string;
|
|
80
|
+
};
|
|
81
|
+
readonly ctx: Context;
|
|
82
|
+
readonly row?: Record<string, unknown>;
|
|
83
|
+
}
|
|
84
|
+
/** A registered policy as stored in the policy table. */
|
|
85
|
+
interface Policy<Context = unknown> {
|
|
86
|
+
readonly on: PolicyOperation;
|
|
87
|
+
readonly table: string;
|
|
88
|
+
readonly when: (context: PolicyContext<Context>) => PolicyDecision;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Input accepted by `definePolicy`. The branded result is the same
|
|
92
|
+
* shape; we keep the input/output split so callers can read JSDoc on the
|
|
93
|
+
* constructor without the type re-exposing `Policy` internals.
|
|
94
|
+
*/
|
|
95
|
+
interface DefinePolicyInput<Context = unknown> {
|
|
96
|
+
on: PolicyOperation;
|
|
97
|
+
/** Logical table name the policy applies to. */
|
|
98
|
+
table: string;
|
|
99
|
+
/**
|
|
100
|
+
* Decision function. Returning a `WhereInput` (read only) AND-merges the
|
|
101
|
+
* predicate; `true` allows; `false` denies; `undefined` skips this policy.
|
|
102
|
+
*
|
|
103
|
+
* NOTE: `count()` is **unsupported** on a policy-restricted table — the
|
|
104
|
+
* reader throws `LunoraError("COUNT_RLS_UNSUPPORTED")` (422). This mirrors
|
|
105
|
+
* kitcn's documented behavior.
|
|
106
|
+
*/
|
|
107
|
+
when: (context: PolicyContext<Context>) => PolicyDecision;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* A named, abstract capability a policy can check with `ctx.auth.can(...)`,
|
|
111
|
+
* instead of branching on raw role strings. Declare one with
|
|
112
|
+
* `definePermission`; grant it to a role via {@link Role.permissions};
|
|
113
|
+
* register the roles with the middleware via {@link RlsOptions.roles}.
|
|
114
|
+
*/
|
|
115
|
+
interface Permission {
|
|
116
|
+
readonly description?: string;
|
|
117
|
+
readonly name: string;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* A role declaration. Roles are string labels attached to the request's
|
|
121
|
+
* identity (via better-auth claims today). `permissions` lists the
|
|
122
|
+
* capabilities the role grants — at request time the middleware unions the
|
|
123
|
+
* permissions of every role in `ctx.auth.roles` so a policy can ask
|
|
124
|
+
* `ctx.auth.can(permission)` rather than enumerate roles.
|
|
125
|
+
*/
|
|
126
|
+
interface Role {
|
|
127
|
+
readonly description?: string;
|
|
128
|
+
readonly name: string;
|
|
129
|
+
/** Permissions this role grants — by {@link Permission} object or bare name. */
|
|
130
|
+
readonly permissions?: ReadonlyArray<Permission | string>;
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Options for the `rls(policies, options)` middleware. `roles` registers the
|
|
134
|
+
* role→permission grants that back `ctx.auth.can(...)`; a role not listed here
|
|
135
|
+
* grants no permissions (so `can` is conservative — it fails closed for
|
|
136
|
+
* unknown roles).
|
|
137
|
+
*/
|
|
138
|
+
interface RlsOptions {
|
|
139
|
+
readonly roles?: ReadonlyArray<Role>;
|
|
140
|
+
}
|
|
141
|
+
export { DefinePolicyInput as D, PolicyOperation as P, Role as R, TypedDefinePolicyInput as T, WhereInput as W, Policy as a, RlsOptions as b, Permission as c, PolicyContext as d, PolicyDecision as e, PolicyDecisionOf as f };
|
package/dist/rls/testing.d.mts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-
|
|
1
|
+
import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-B-pIn8rE.mjs";
|
|
2
2
|
import "../data-model.mjs";
|
|
3
3
|
/**
|
|
4
|
-
* The slice of a request identity a policy reads. Mirrors the
|
|
5
|
-
* `PolicyContext.auth` shape the middleware builds at request time — every
|
|
6
|
-
* field is optional and defaults the same way the middleware defaults it
|
|
7
|
-
* (`userId`/`identity` → `null`, `roles` → `[]`).
|
|
8
|
-
*/
|
|
4
|
+
* The slice of a request identity a policy reads. Mirrors the
|
|
5
|
+
* `PolicyContext.auth` shape the middleware builds at request time — every
|
|
6
|
+
* field is optional and defaults the same way the middleware defaults it
|
|
7
|
+
* (`userId`/`identity` → `null`, `roles` → `[]`).
|
|
8
|
+
*/
|
|
9
9
|
interface TestIdentity {
|
|
10
10
|
/** Raw identity claims a policy may branch on (`auth.identity.email`, …). */
|
|
11
11
|
identity?: Record<string, unknown> | null;
|
|
@@ -17,32 +17,32 @@ interface TestIdentity {
|
|
|
17
17
|
/** Options for {@link expectPolicy}. */
|
|
18
18
|
interface ExpectPolicyOptions<Context = unknown> {
|
|
19
19
|
/**
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
* The procedure context a policy reads via `ctx` (e.g. `ctx.orgId`). Held
|
|
21
|
+
* for the whole harness; pass a fresh `expectPolicy(..., { ctx })` for a
|
|
22
|
+
* different context. Defaults to an empty object.
|
|
23
|
+
*/
|
|
24
24
|
ctx?: Context;
|
|
25
25
|
/**
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
26
|
+
* Role→permission grants backing `auth.can(...)` — the same registry passed
|
|
27
|
+
* to `rls(policies, { roles })`. A role not listed here grants nothing, so
|
|
28
|
+
* `can(...)` fails closed exactly as it does in production.
|
|
29
|
+
*/
|
|
30
30
|
roles?: ReadonlyArray<Role>;
|
|
31
31
|
}
|
|
32
32
|
/** A harness bound to one identity; answers can/cannot for an `(op, table, row)`. */
|
|
33
33
|
interface BoundPolicyAssertion {
|
|
34
34
|
/**
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
35
|
+
* Would this identity be **allowed** the operation on `row`?
|
|
36
|
+
*
|
|
37
|
+
* - `read` — is `row` visible? `true` when the table has no read policy (unrestricted), or when the effective read `baseWhere` matches `row`.
|
|
38
|
+
* - `insert` — is the candidate `row` allowed by the insert policies?
|
|
39
|
+
* - `update` / `delete` — is the pre-write `row` allowed? For `update` pass `nextRow` to also assert the post-image (WITH CHECK) — a policy can't be satisfied by the old row while the patch reassigns it to another tenant.
|
|
40
|
+
*
|
|
41
|
+
* A table with **no** policy in the list is unguarded → always `true`
|
|
42
|
+
* (mirrors the middleware passing such tables through unwrapped). A table
|
|
43
|
+
* that participates but declares no policy for the write `op` denies
|
|
44
|
+
* (default-DENY), exactly as the middleware does.
|
|
45
|
+
*/
|
|
46
46
|
can: (op: PolicyOperation, table: string, row?: Record<string, unknown>, nextRow?: Record<string, unknown>) => boolean;
|
|
47
47
|
/** Negation of {@link BoundPolicyAssertion.can} — reads more naturally in a denial test. */
|
|
48
48
|
cannot: (op: PolicyOperation, table: string, row?: Record<string, unknown>, nextRow?: Record<string, unknown>) => boolean;
|
|
@@ -53,11 +53,11 @@ interface PolicyAssertion {
|
|
|
53
53
|
as: (identity?: TestIdentity | null) => BoundPolicyAssertion;
|
|
54
54
|
}
|
|
55
55
|
/**
|
|
56
|
-
* Build an in-process assertion harness over a policy set. Reuses the `rls()`
|
|
57
|
-
* middleware's own evaluation primitives, so an assertion is faithful to
|
|
58
|
-
* request-time behaviour by construction.
|
|
59
|
-
* @param policies the policy list, typically from `definePolicies([...])`.
|
|
60
|
-
* @param options role registry + procedure `ctx` (see {@link ExpectPolicyOptions}).
|
|
61
|
-
*/
|
|
56
|
+
* Build an in-process assertion harness over a policy set. Reuses the `rls()`
|
|
57
|
+
* middleware's own evaluation primitives, so an assertion is faithful to
|
|
58
|
+
* request-time behaviour by construction.
|
|
59
|
+
* @param policies the policy list, typically from `definePolicies([...])`.
|
|
60
|
+
* @param options role registry + procedure `ctx` (see {@link ExpectPolicyOptions}).
|
|
61
|
+
*/
|
|
62
62
|
declare const expectPolicy: <Context = unknown>(policies: ReadonlyArray<Policy<Context>>, options?: ExpectPolicyOptions<Context>) => PolicyAssertion;
|
|
63
63
|
export { BoundPolicyAssertion, ExpectPolicyOptions, PolicyAssertion, TestIdentity, expectPolicy };
|
package/dist/rls/testing.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-
|
|
1
|
+
import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-CdPDEjhz.js";
|
|
2
2
|
import "../data-model.js";
|
|
3
3
|
/**
|
|
4
|
-
* The slice of a request identity a policy reads. Mirrors the
|
|
5
|
-
* `PolicyContext.auth` shape the middleware builds at request time — every
|
|
6
|
-
* field is optional and defaults the same way the middleware defaults it
|
|
7
|
-
* (`userId`/`identity` → `null`, `roles` → `[]`).
|
|
8
|
-
*/
|
|
4
|
+
* The slice of a request identity a policy reads. Mirrors the
|
|
5
|
+
* `PolicyContext.auth` shape the middleware builds at request time — every
|
|
6
|
+
* field is optional and defaults the same way the middleware defaults it
|
|
7
|
+
* (`userId`/`identity` → `null`, `roles` → `[]`).
|
|
8
|
+
*/
|
|
9
9
|
interface TestIdentity {
|
|
10
10
|
/** Raw identity claims a policy may branch on (`auth.identity.email`, …). */
|
|
11
11
|
identity?: Record<string, unknown> | null;
|
|
@@ -17,32 +17,32 @@ interface TestIdentity {
|
|
|
17
17
|
/** Options for {@link expectPolicy}. */
|
|
18
18
|
interface ExpectPolicyOptions<Context = unknown> {
|
|
19
19
|
/**
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
* The procedure context a policy reads via `ctx` (e.g. `ctx.orgId`). Held
|
|
21
|
+
* for the whole harness; pass a fresh `expectPolicy(..., { ctx })` for a
|
|
22
|
+
* different context. Defaults to an empty object.
|
|
23
|
+
*/
|
|
24
24
|
ctx?: Context;
|
|
25
25
|
/**
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
26
|
+
* Role→permission grants backing `auth.can(...)` — the same registry passed
|
|
27
|
+
* to `rls(policies, { roles })`. A role not listed here grants nothing, so
|
|
28
|
+
* `can(...)` fails closed exactly as it does in production.
|
|
29
|
+
*/
|
|
30
30
|
roles?: ReadonlyArray<Role>;
|
|
31
31
|
}
|
|
32
32
|
/** A harness bound to one identity; answers can/cannot for an `(op, table, row)`. */
|
|
33
33
|
interface BoundPolicyAssertion {
|
|
34
34
|
/**
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
35
|
+
* Would this identity be **allowed** the operation on `row`?
|
|
36
|
+
*
|
|
37
|
+
* - `read` — is `row` visible? `true` when the table has no read policy (unrestricted), or when the effective read `baseWhere` matches `row`.
|
|
38
|
+
* - `insert` — is the candidate `row` allowed by the insert policies?
|
|
39
|
+
* - `update` / `delete` — is the pre-write `row` allowed? For `update` pass `nextRow` to also assert the post-image (WITH CHECK) — a policy can't be satisfied by the old row while the patch reassigns it to another tenant.
|
|
40
|
+
*
|
|
41
|
+
* A table with **no** policy in the list is unguarded → always `true`
|
|
42
|
+
* (mirrors the middleware passing such tables through unwrapped). A table
|
|
43
|
+
* that participates but declares no policy for the write `op` denies
|
|
44
|
+
* (default-DENY), exactly as the middleware does.
|
|
45
|
+
*/
|
|
46
46
|
can: (op: PolicyOperation, table: string, row?: Record<string, unknown>, nextRow?: Record<string, unknown>) => boolean;
|
|
47
47
|
/** Negation of {@link BoundPolicyAssertion.can} — reads more naturally in a denial test. */
|
|
48
48
|
cannot: (op: PolicyOperation, table: string, row?: Record<string, unknown>, nextRow?: Record<string, unknown>) => boolean;
|
|
@@ -53,11 +53,11 @@ interface PolicyAssertion {
|
|
|
53
53
|
as: (identity?: TestIdentity | null) => BoundPolicyAssertion;
|
|
54
54
|
}
|
|
55
55
|
/**
|
|
56
|
-
* Build an in-process assertion harness over a policy set. Reuses the `rls()`
|
|
57
|
-
* middleware's own evaluation primitives, so an assertion is faithful to
|
|
58
|
-
* request-time behaviour by construction.
|
|
59
|
-
* @param policies the policy list, typically from `definePolicies([...])`.
|
|
60
|
-
* @param options role registry + procedure `ctx` (see {@link ExpectPolicyOptions}).
|
|
61
|
-
*/
|
|
56
|
+
* Build an in-process assertion harness over a policy set. Reuses the `rls()`
|
|
57
|
+
* middleware's own evaluation primitives, so an assertion is faithful to
|
|
58
|
+
* request-time behaviour by construction.
|
|
59
|
+
* @param policies the policy list, typically from `definePolicies([...])`.
|
|
60
|
+
* @param options role registry + procedure `ctx` (see {@link ExpectPolicyOptions}).
|
|
61
|
+
*/
|
|
62
62
|
declare const expectPolicy: <Context = unknown>(policies: ReadonlyArray<Policy<Context>>, options?: ExpectPolicyOptions<Context>) => PolicyAssertion;
|
|
63
63
|
export { BoundPolicyAssertion, ExpectPolicyOptions, PolicyAssertion, TestIdentity, expectPolicy };
|