@lunora/server 1.0.0-alpha.4 → 1.0.0-alpha.41

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.
Files changed (68) hide show
  1. package/LICENSE.md +219 -0
  2. package/README.md +50 -0
  3. package/dist/data-model.d.mts +231 -156
  4. package/dist/data-model.d.ts +231 -156
  5. package/dist/data-model.mjs +0 -1
  6. package/dist/drizzle.mjs +1 -1
  7. package/dist/index.d.mts +1304 -831
  8. package/dist/index.d.ts +1304 -831
  9. package/dist/index.mjs +1 -24
  10. package/dist/otel.d.mts +543 -0
  11. package/dist/otel.d.ts +543 -0
  12. package/dist/otel.mjs +1 -0
  13. package/dist/packem_shared/LunoraEnvError-CgpI2Mm_.mjs +3 -0
  14. package/dist/packem_shared/LunoraError-LVhdU0Lo.mjs +1 -0
  15. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-CF_9uiu1.mjs +1 -0
  16. package/dist/packem_shared/allowAll-BnyNbJZT.mjs +1 -0
  17. package/dist/packem_shared/asBucketStorage-1pFfH-Tn.mjs +1 -0
  18. package/dist/packem_shared/bindOrm-Bp9hsM2q.mjs +1 -0
  19. package/dist/packem_shared/buildRlsReadRegistry-WdiqSj87.mjs +1 -0
  20. package/dist/packem_shared/composePluginMiddleware-COr09CXA.mjs +1 -0
  21. package/dist/packem_shared/context-identity-GunnA6La.mjs +1 -0
  22. package/dist/packem_shared/createPolicyDsl-sV1swpkD.mjs +1 -0
  23. package/dist/packem_shared/createSecrets-CgVPiW2C.mjs +1 -0
  24. package/dist/packem_shared/defineAggregateIndex-CYuH6IbJ.mjs +1 -0
  25. package/dist/packem_shared/defineIdentity-B7gfAgxx.mjs +1 -0
  26. package/dist/packem_shared/defineMigration-Bfpwxv2f.mjs +1 -0
  27. package/dist/packem_shared/defineMutator-BgpQ-xUo.mjs +1 -0
  28. package/dist/packem_shared/defineShape-Ds8uNqzX.mjs +1 -0
  29. package/dist/packem_shared/defineStorageRule-BDu01PUn.mjs +1 -0
  30. package/dist/packem_shared/functions-CDC08CWY.mjs +1 -0
  31. package/dist/packem_shared/httpAction-C14NuF3V.mjs +4 -0
  32. package/dist/packem_shared/initLunora-CHh1EmR4.mjs +1 -0
  33. package/dist/packem_shared/mask-C6Bi78qj.mjs +1 -0
  34. package/dist/packem_shared/onConnect-CEtRmUpJ.mjs +1 -0
  35. package/dist/packem_shared/policy-tag-Dprt9JWo.mjs +1 -0
  36. package/dist/packem_shared/protectPublic-BhKewPqm.mjs +1 -0
  37. package/dist/packem_shared/rls-_iVsPvhX.mjs +1 -0
  38. package/dist/packem_shared/run-middleware-BeEEqmdE.mjs +1 -0
  39. package/dist/packem_shared/storageRules-BptPZbi8.mjs +1 -0
  40. package/dist/packem_shared/types.d-C4CMJK8x.d.mts +141 -0
  41. package/dist/packem_shared/types.d-DdYF8E18.d.ts +141 -0
  42. package/dist/rls/testing.d.mts +31 -31
  43. package/dist/rls/testing.d.ts +31 -31
  44. package/dist/rls/testing.mjs +1 -49
  45. package/dist/types.d.mts +1163 -440
  46. package/dist/types.d.ts +1163 -440
  47. package/dist/types.mjs +1 -31
  48. package/package.json +18 -5
  49. package/dist/packem_shared/LunoraEnvError-DjFkpkSP.mjs +0 -187
  50. package/dist/packem_shared/LunoraError-DhggBJZF.mjs +0 -51
  51. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-BgBQsqQ-.mjs +0 -114
  52. package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
  53. package/dist/packem_shared/bindOrm-Ce57S3N9.mjs +0 -128
  54. package/dist/packem_shared/composePluginMiddleware-Ck5_TUO8.mjs +0 -100
  55. package/dist/packem_shared/createPolicyDsl-De67zPDS.mjs +0 -29
  56. package/dist/packem_shared/defineAggregateIndex-C2gT1GzM.mjs +0 -252
  57. package/dist/packem_shared/defineMigration-CAJLr6fx.mjs +0 -8
  58. package/dist/packem_shared/defineStorageRule-qu0mpilX.mjs +0 -20
  59. package/dist/packem_shared/httpAction-B7FYUEgr.mjs +0 -340
  60. package/dist/packem_shared/initLunora-CATvPsVt.mjs +0 -86
  61. package/dist/packem_shared/mask-eCUYOwhd.mjs +0 -211
  62. package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
  63. package/dist/packem_shared/protectPublic-BjFkQ_Or.mjs +0 -15
  64. package/dist/packem_shared/rls-Bi9HiyDC.mjs +0 -567
  65. package/dist/packem_shared/run-middleware-CYQOuoV6.mjs +0 -18
  66. package/dist/packem_shared/storageRules-4a30FSpI.mjs +0 -88
  67. package/dist/packem_shared/types.d-BDY0FYHK.d.ts +0 -135
  68. package/dist/packem_shared/types.d-DmvyEMD6.d.mts +0 -135
@@ -0,0 +1,4 @@
1
+ import{toErrorBody as E}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as v}from"@lunora/values";import{Hono as P}from"hono";import{LunoraError as p}from"./LunoraError-LVhdU0Lo.mjs";const H=e=>async t=>e(t.get("lunora"),t.req.raw),z=()=>{const e=new P;return e.use("*",async(t,a)=>{const r=t.env.__lunoraCtx;if(!r)throw new p("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");t.set("lunora",r),await a()}),e},k=e=>e.kind==="optional"?e._meta?.inner??e:e,y=(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}},_=(e,t,a)=>{const r=k(e);if(r.kind==="array"){const o=t.req.queries(a);if(o===void 0)return;const n=r._meta?.inner;return o.map(c=>y(n?.kind??"string",c))}const s=t.req.query(a);return s===void 0?void 0:y(r.kind,s)},S=(e,t)=>{const a={};for(const r of Object.keys(e)){const s=e[r];s&&(a[r]=_(s,t,r))}return R(e,a,"searchParams")},N=(e,t)=>{const a=t.req.param(),r={};for(const s of Object.keys(e)){const o=e[s];if(!o)continue;const n=a[s];r[s]=n===void 0?void 0:y(k(o).kind,n)}return R(e,r,"params")},x=async(e,t)=>{let a;try{a=await t.req.json()}catch{throw new p("BAD_REQUEST","Invalid JSON body")}if(typeof a!="object"||a===null||Array.isArray(a))throw new p("BAD_REQUEST","Expected a JSON object body");return R(e,a,"body")},A=(e,t)=>{try{return e.parse(t)}catch(a){throw a instanceof v?new p("INTERNAL_SERVER_ERROR",`Response did not match the declared output schema: ${a.message}`):a}},O=e=>{if(e instanceof v)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(e instanceof p){const{body:t,redacted:a,status:r}=E(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return a&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:t.code,error:t.message},{status:r})}throw e},q=(e,t)=>async a=>{try{const r=a.get("lunora"),s=Object.keys(e.searchParams).length>0?S(e.searchParams,a):{},o=Object.keys(e.params).length>0?N(e.params,a):{},n=Object.keys(e.body).length>0?await x(e.body,a):{},c=await t({body:n,ctx:r,params:o,searchParams:s}),i=e.output?A(e.output,c):c,u={};e.cacheControl&&(u["cache-control"]=e.cacheControl),e.cacheTag&&(u["cache-tag"]=e.cacheTag),e.vary&&(u.vary=e.vary);const m=Object.keys(u).length>0;return i===void 0?new Response(null,{headers:m?u:void 0,status:204}):Response.json(i,{headers:m?u:void 0})}catch(r){return O(r)}},g=(e,t)=>{const a=JSON.stringify(e);return`${t?`event: ${t}
2
+ `:""}data: ${a}
3
+
4
+ `},C=(e,t)=>async a=>{let r,s;try{r=Object.keys(e.searchParams).length>0?S(e.searchParams,a):{},s=Object.keys(e.params).length>0?N(e.params,a):{}}catch(d){return O(d)}const o=a.get("lunora"),n=a.req.raw,c=new TextEncoder,i=new AbortController;if(n.signal.aborted)return i.abort(),new Response(new ReadableStream({start:d=>{d.close()}}),{headers:{"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"}});const u=()=>{i.abort()};n.signal.addEventListener("abort",u,{once:!0});const m=new ReadableStream({cancel(){n.signal.removeEventListener("abort",u),i.abort()},async start(d){try{const f=t({ctx:o,params:s,request:n,searchParams:r,signal:i.signal});for await(const b of f){if(i.signal.aborted)break;d.enqueue(c.encode(g(b)))}d.enqueue(c.encode(g({},"complete")))}catch(f){const{body:b,redacted:j}=E(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});j&&console.error("[lunora] unhandled stream handler error:",f),d.enqueue(c.encode(g({code:b.code,message:b.message},"error")))}finally{n.signal.removeEventListener("abort",u),d.close()}}}),T={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"};return new Response(m,{headers:T})},l=e=>({body:t=>l({...e,body:{...e.body,...t}}),cacheControl:t=>l({...e,cacheControl:t}),cacheTag:t=>l({...e,cacheTag:t}),handler:t=>q(e,t),output:t=>l({...e,output:t}),params:t=>l({...e,params:{...e.params,...t}}),searchParams:t=>l({...e,searchParams:{...e.searchParams,...t}}),stream:t=>C(e,t),vary:t=>l({...e,vary:t})}),h=e=>t=>l({body:{},method:e,params:{},path:t,searchParams:{}}),U={delete:h("DELETE"),get:h("GET"),head:h("HEAD"),options:h("OPTIONS"),patch:h("PATCH"),post:h("POST"),put:h("PUT")},$=/^bytes=(\d*)-(\d*)$/,w=e=>e.startsWith('"')||e.startsWith('W/"')?e:`"${e}"`,I=e=>{for(let t=0;t<e.length;t+=1){const a=e.codePointAt(t);if(a===13||a===10||a===0)return!1}return!0},L=(e,t)=>{if(e===null)return{kind:"full"};const a=$.exec(e.trim());if(!a)return{kind:"full"};const r=a[1]??"",s=a[2]??"";if(r===""&&s==="")return{kind:"full"};let o,n;if(r===""){const c=Number(s);if(c===0)return{kind:"unsatisfiable"};o=Math.max(0,t-c),n=t-1}else o=Number(r),n=s===""?t-1:Math.min(Number(s),t-1);return o>n||o>=t?{kind:"unsatisfiable"}:{end:n,kind:"partial",start:o}},W=async(e,t,a)=>{const r=await e.storage.download(t);if(!r)return new Response("Not Found",{status:404});const s=r.httpMetadata?.contentType,o={"accept-ranges":"bytes","content-type":s!==void 0&&I(s)?s:"application/octet-stream",etag:w(r.etag)};r.sha256Base64!==void 0&&(o["repr-digest"]=`sha-256=:${r.sha256Base64}:`);const n=L(a.headers.get("range"),r.size);if(n.kind==="unsatisfiable")return r.body?.cancel().catch(()=>{}),new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(r.size)}`,"content-type":"text/plain; charset=utf-8",etag:w(r.etag)},status:416});if(n.kind==="full")return new Response(r.body,{headers:{...o,"content-length":String(r.size)},status:200});r.body?.cancel().catch(()=>{});const c=n.end-n.start+1,i=await e.storage.download(t,{range:{length:c,offset:n.start}});return i?new Response(i.body,{headers:{...o,"content-length":String(c),"content-range":`bytes ${String(n.start)}-${String(n.end)}/${String(r.size)}`},status:206}):new Response("Not Found",{status:404})};export{H as httpAction,U as httpRoute,z as httpRouter,I as isSafeHeaderValue,W as serveStorageObject};
@@ -0,0 +1 @@
1
+ import{s as c}from"./functions-CDC08CWY.mjs";import{l as g}from"./policy-tag-Dprt9JWo.mjs";import{l as p}from"./run-middleware-BeEEqmdE.mjs";const x=(r,e)=>p(r,e,a=>a),w=(r,e,a,t)=>async(i,o)=>{const d=c(r,o),n=await x(e,i),l=await a({args:d,ctx:n});return t?t.parse(l):l},y=(r,e,a)=>(t,i,o)=>{const d=c(r,i);return(async function*(){const n=await x(e,t),l=a({args:d,ctx:n,signal:o})[Symbol.asyncIterator]();try{for(;;){if(o.aborted)return;const u=await l.next();if(u.done||o.aborted)return;yield u.value}}finally{await l.return?.()}})()},m=r=>{const e=[];for(const a of r){const t=g(a);t&&e.push(t)}return e.length>0?{tags:e}:void 0},s=(r,e,a)=>({__lunoraProcedure:r,...a?{__lunoraVisibility:a}:{},input:t=>s(r,{...e,args:{...e.args,...t}},a),[r]:t=>{const i=m(e.middlewares);return{args:e.args,...e.expose?{expose:e.expose}:{},handler:w(e.args,e.middlewares,t,e.output),kind:r,...i?{rls:i}:{},...a?{visibility:a}:{},...e.x402?{x402:e.x402}:{}}},output:t=>s(r,{...e,output:t},a),...r==="query"?{stream:t=>{const i=m(e.middlewares);return{args:e.args,...e.expose?{expose:e.expose}:{},handler:y(e.args,e.middlewares,t),kind:"stream",...i?{rls:i}:{},...a?{visibility:a}:{},...e.x402?{x402:e.x402}:{}}}}:{},use:t=>s(r,{...e,middlewares:[...e.middlewares,t]},a),...a?{}:{expose:t=>s(r,{...e,expose:t},a)},...a?{}:{x402:t=>s(r,{...e,x402:t},a)}}),q={dataModel:()=>({create:r=>({action:s("action",{args:{},middlewares:[]}),internalAction:s("action",{args:{},middlewares:[]},"internal"),internalMutation:s("mutation",{args:{},middlewares:[]},"internal"),internalQuery:s("query",{args:{},middlewares:[]},"internal"),mutation:s("mutation",{args:{},middlewares:[]}),query:s("query",{args:{},middlewares:[]})})})};export{q as initLunora};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"./LunoraError-LVhdU0Lo.mjs";import{bindOrm as N,bindTableFacade as x}from"./bindOrm-Bp9hsM2q.mjs";const S=a=>typeof a=="string"?a:a.name,I=a=>{const i=new Map;for(const s of a??[])i.set(s.name,new Set((s.permissions??[]).map(c=>S(c))));return i},M=a=>{let i=2166136261;for(let s=0;s<a.length;s+=1)i^=a.codePointAt(s)??0,i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},O=(a,i,s)=>{try{return a==="redact"?null:a==="hash"?i==null?i:M(typeof i=="string"?i:JSON.stringify(i)):a(i,s)}catch{return null}},h=(a,i,s)=>{const c={...a};for(const[f,w]of Object.entries(i))f in c&&(c[f]=O(w,a[f],{...s,column:f,row:a}));return c},m=(a,i,s)=>({...a,page:a.page.map(c=>h(c,i,s))}),A=(a,i,s,c)=>{if(typeof a!="function")return;const f=new Set,w=()=>new Proxy({},{get:()=>y=>(typeof y=="string"&&f.add(y),w())});a(w());for(const y of f)if(y in i)throw new g("MASK_UNSUPPORTED",`${c}() filtering "${s}" by masked column "${y}" is not supported`)},k=a=>{if(typeof a!="object"||a===null||Array.isArray(a))return!1;const i=a;return typeof i.findMany=="function"&&typeof i.withSearchIndex=="function"},v=(a,i,s)=>{const c=(t,r,n)=>({collect:async()=>(await t.collect()).map(e=>h(e,r,s)),filter:e=>c(t.filter(o=>e(h(o,r,s))),r,n),first:async()=>{const e=await t.first();return e?h(e,r,s):null},order:e=>c(t.order(e),r,n),paginate:async e=>m(await t.paginate(e),r,s),take:async e=>(await t.take(e)).map(o=>h(o,r,s)),unique:async()=>{const e=await t.unique();return e?h(e,r,s):null},withIndex:(e,o)=>(A(o,r,n,"withIndex"),c(t.withIndex(e,o),r,n)),withSearchIndex:(e,o)=>(A(o,r,n,"withSearchIndex"),c(t.withSearchIndex(e,o),r,n)),withGeoIndex:(e,o)=>c(t.withGeoIndex(e,o),r,n)}),f=async(t,r)=>{if(a.lookupById){const d=await a.lookupById(t,r);return d?{row:d.row,tableName:i.has(d.tableName)?d.tableName:void 0}:{row:null,tableName:void 0}}const n=await a.get(t,r);if(!n)return{row:null,tableName:void 0};let e;r===void 0?e=[...i.keys()]:i.has(r)?e=[r]:e=[];const o=await Promise.all(e.map(async d=>(await a.findFirst(d,{limit:1,where:{_id:t}}))?._id===t?d:void 0));return{row:n,tableName:o.find(d=>d!==void 0)}},w=(t,r,n)=>{const e=i.get(t);if(!e)return;const o=r.find(d=>typeof d=="string"&&d in e);if(o!==void 0)throw new g("MASK_UNSUPPORTED",`${n}() over masked column "${o}" on "${t}" is not supported`)},y=(t,r)=>{if(!(!t||typeof t!="object"||Array.isArray(t)))for(const[n,e]of Object.entries(t))if(n==="AND"||n==="OR"){if(Array.isArray(e))for(const o of e)y(o,r)}else n==="NOT"?y(e,r):n.startsWith("__")||r.add(n)},u=(t,r,n)=>{const e=i.get(t);if(!e||r===void 0)return;const o=new Set;y(r,o);for(const d of o)if(d in e)throw new g("MASK_UNSUPPORTED",`${n}() filtering "${t}" by masked column "${d}" is not supported`)},l=(t,r,n)=>{const e=i.get(t);if(!(!e||!Array.isArray(r))){for(const o of r)if(o&&typeof o=="object"&&!Array.isArray(o)){for(const d of Object.keys(o))if(d in e)throw new g("MASK_UNSUPPORTED",`${n}() ordering "${t}" by masked column "${d}" is not supported`)}}},p={...a,async deleteWhere(t,r,n){if(u(t,r,"deleteMany({ where })"),a.deleteWhere===void 0)throw new g("INTERNAL",`ctx.db.${t}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return a.deleteWhere(t,r,n)},async patchWhere(t,r,n){if(u(t,r.where,"patchMany({ where })"),a.patchWhere===void 0)throw new g("INTERNAL",`ctx.db.${t}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return a.patchWhere(t,r,n)},aggregate(t,r){return w(t,[r.field],"aggregate"),u(t,r.where,"aggregate"),a.aggregate(t,r)},count(t,r){const n=r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,e=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:r;return u(t,e,"count"),n&&u(t,n.baseWhere,"count"),a.count(t,r)},async findFirst(t,r){u(t,r?.where,"findFirst"),u(t,r?.baseWhere,"findFirst"),l(t,r?.orderBy,"findFirst");const n=await a.findFirst(t,r),e=i.get(t);return n&&e?h(n,e,s):n},async findFirstOrThrow(t,r){u(t,r?.where,"findFirstOrThrow"),u(t,r?.baseWhere,"findFirstOrThrow"),l(t,r?.orderBy,"findFirstOrThrow");const n=await a.findFirstOrThrow(t,r),e=i.get(t);return e?h(n,e,s):n},async findMany(t,r){u(t,r?.where,"findMany"),u(t,r?.baseWhere,"findMany"),l(t,r?.orderBy,"findMany");const n=await a.findMany(t,r),e=i.get(t);return e?m(n,e,s):n},async get(t,r){const{row:n,tableName:e}=await f(t,r),o=e===void 0?void 0:i.get(e);return!n||!o?n:h(n,o,s)},groupBy(t,r){return w(t,[...r.by,r.agg?.field],"groupBy"),u(t,r.where,"groupBy"),a.groupBy(t,r)},query(t){const r=a.query(t),n=i.get(t);return n?c(r,n,t):r},async rankPage(t,r,n){const e=await a.rankPage(t,r,n),o=i.get(t);return o?m(e,o,s):e}},b=p;for(const t of i.keys())k(a[t])&&(b[t]=x(p,t));return p},F=(a,i={})=>{const s=new Map(Object.entries(a)),c=I(i.roles);return async({ctx:f,next:w})=>{const y=f.auth??{},u=await y.getIdentity?.()??null,l=y.roles??[],p=new Set;for(const e of l)for(const o of c.get(e)??[])p.add(o);const b={auth:{can:e=>p.has(S(e)),identity:u,roles:l,userId:y.userId??null},ctx:f};if(i.bypass?.(b))return w();const t=v(f.db,s,b),r={db:t},{orm:n}=f;return n!==null&&typeof n=="object"&&(r.orm=N(t)),w({ctx:r})}};export{F as mask};
@@ -0,0 +1 @@
1
+ const i=(n,c)=>({args:{},handler:(t,e)=>c(t,e),kind:"mutation",lifecycle:n,visibility:"internal"}),o=n=>i("connect",n),s=n=>i("disconnect",n);export{o as onConnect,s as onDisconnect};
@@ -0,0 +1 @@
1
+ const o=Symbol.for("lunora.rls.middleware-policies"),l=(e,r)=>(Object.defineProperty(e,o,{configurable:!0,enumerable:!1,value:r}),e),t=e=>{if(!(e===null||typeof e!="function"&&typeof e!="object"))return e[o]};export{t as l,l as r};
@@ -0,0 +1 @@
1
+ import{l as n}from"./run-middleware-BeEEqmdE.mjs";const e=t=>{const r=[t.rateLimit,t.captcha,...t.use??[]].filter(c=>c!==void 0);return async({ctx:c,next:o})=>n(r,c,i=>o({ctx:i}))};export{e as protectPublic};
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"./LunoraError-LVhdU0Lo.mjs";import{bindOrm as x,bindTableFacade as P}from"./bindOrm-Bp9hsM2q.mjs";import{r as U}from"./policy-tag-Dprt9JWo.mjs";import{deny as j}from"./allowAll-BnyNbJZT.mjs";const S=500,N=(t,r,s)=>{const i=r??S;if(t>i)throw new p("BAD_REQUEST",`${s}: batch of ${String(t)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},F=j(),C=Symbol.for("lunora.ctxdb.rls-unwrap"),$=t=>{const r=new Map;for(const s of t){const i=r.get(s.table)??[];i.push(s),r.set(s.table,i)}return r},q=(t,r)=>{const s=[];let i=!1;for(const u of t){if(u.on!=="read")continue;const c=u.when(r);if(c!==void 0){if(c===!0){i=!0;break}c!==!1&&s.push(c)}}if(!i)return s.length===0?F:s.length===1?s[0]:{OR:s}},D=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),L=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],m=t=>{const r=typeof t;return r==="number"||r==="string"||r==="bigint"},z=(t,r)=>!("lt"in r&&(!m(t)||!m(r.lt)||t>=r.lt)||"lte"in r&&(!m(t)||!m(r.lte)||t>r.lte)||"gt"in r&&(!m(t)||!m(r.gt)||t<=r.gt)||"gte"in r&&(!m(t)||!m(r.gte)||t<r.gte)),Q=(t,r)=>{if("in"in r){const s=r.in;if(!Array.isArray(s)||!s.includes(t))return!1}if("notIn"in r){const s=r.notIn;if(Array.isArray(s)&&s.includes(t))return!1}if("contains"in r){const s=r.contains;if(typeof t!="string"||typeof s!="string"||!t.includes(s))return!1}return!("isNull"in r&&r.isNull===!0!=(t==null))},G=(t,r)=>"eq"in r&&t!==r.eq||"ne"in r&&t===r.ne?!1:Q(t,r)&&z(t,r),H=(t,r,s,i)=>r==="AND"?Array.isArray(s)&&s.every(u=>i(t,u)):r==="OR"?Array.isArray(s)&&s.some(u=>i(t,u)):!i(t,s??{}),I=t=>t==="AND"||t==="OR"||t==="NOT",J=t=>D(t)&&Object.keys(t).every(r=>L.includes(r)),K=["every","is","isNot","none","some"],V=t=>D(t)&&Object.keys(t).length>0&&Object.keys(t).every(r=>K.includes(r)),R=t=>Object.keys(t).some(r=>{const s=t[r];return I(r)?r==="NOT"?R(s??{}):Array.isArray(s)&&s.some(i=>R(i??{})):V(s)}),k=(t,r)=>{for(const s of Object.keys(r)){const i=r[s];if(I(s)){if(!H(t,s,i,k))return!1;continue}const u=t[s];if(J(i)){if(!G(u,i))return!1;continue}if(u!==i)return!1}return!0},X=(t,r,s)=>{const i=t.when({...r,row:s});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(R(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return k(s,i)},Y=(t,r,s)=>{const i=t.when(r);if(i===void 0||i===!0)return s===void 0||X(t,r,s);if(i===!1)return!1;if(R(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!k(r.row,i)?!1:s===void 0||k(s,i)},M=(t,r,s,i)=>{let u=!1;for(const c of t)if(c.on===r&&(u=!0,!Y(c,s,i)))return!1;return u},E=t=>t??{},Z=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),ee=(t,r)=>r===void 0?!0:t==="restrictsCounts"?typeof r=="boolean":t==="relationBaseWhere"?typeof r=="function":D(r),te=t=>{const r=Object.keys(t);return r.length===0?!1:r.every(s=>Z.has(s)&&ee(s,t[s]))},re=t=>t===void 0?{}:D(t)&&te(t)?t:{where:t},b=(t,r)=>!r||Object.keys(r).length===0?t:!t||Object.keys(t).length===0?r:{AND:[r,t]},ne=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return!1;const r=t;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},ae=(t,r,s,i)=>{const u=new Map,c=e=>{const n=u.get(e);if(n)return n;const a=s.get(e);if(!a||a.length===0||!a.some(l=>l.on==="read")){const l={baseWhere:void 0,restricts:!1};return u.set(e,l),l}const o={baseWhere:q(a,i),restricts:!0};return u.set(e,o),o},f=e=>c(e).restricts?r:t,y=e=>c(e).baseWhere,v=async(e,n)=>{if(r.lookupById){const h=await r.lookupById(e,n);return h?{row:h.row,tableName:s.has(h.tableName)?h.tableName:void 0}:{row:null,tableName:void 0}}const a=await r.get(e,n);if(!a)return{row:null,tableName:void 0};const o=n!==void 0&&s.has(n)?[n]:[],l=n===void 0?[...s.keys()]:o,d=await Promise.all(l.map(async h=>(await r.findFirst(h,{limit:1,where:{_id:e}}))?._id===e?h:void 0));return{row:a,tableName:d.find(h=>h!==void 0)}},B=async(e,n)=>{const a=await v(e,n);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},w=async(e,n,a,o,l)=>{const d=await B(e,l);if(!d)return a(t);const h=s.get(d.tableName);if(h){const _=o?o(d.row):void 0;if(!M(h,n,{...i,row:d.row},_))throw new p("FORBIDDEN",`${n} denied by policy`)}return a(r)},W=(e,n)=>{const{baseWhere:a,restricts:o}=c(e);if(o)throw new p("COUNT_RLS_UNSUPPORTED",`${n}() is not supported on "${e}" inside an RLS-restricted context`);return a},O=t.rankBefore,g={...t,async count(e,n){const{baseWhere:a,restricts:o}=c(e),l=re(n);return f(e).count(e,{...l,baseWhere:b(l.baseWhere,a),relationBaseWhere:y,restrictsCounts:(l.restrictsCounts??!1)||o})},delete:(e,n,a)=>w(e,"delete",o=>o.delete(e,n,a),void 0,n),async deleteAll(e,n){const a=Math.max(1,n?.chunkSize??S),{baseWhere:o}=c(e);let l=0;for(;;){const d=(await f(e).findMany(e,{baseWhere:o,limit:a,relationBaseWhere:y})).page.map(h=>String(h._id));if(d.length===0)break;for(const h of d)await w(h,"delete",_=>_.delete(h,void 0,n?.hard===void 0?void 0:{hard:n.hard})),l+=1;if(d.length<a)break}return{deleted:l}},async deleteMany(e,n,a){N(e.length,n?.limit,"deleteMany");for(const o of e)await w(o,"delete",l=>l.delete(o,a),void 0,a);return{deleted:e.length}},async deleteWhere(e,n,a){const{baseWhere:o}=c(e),l=(await f(e).findMany(e,{baseWhere:b(n,o),relationBaseWhere:y})).page.map(d=>String(d._id));return N(l.length,a?.limit,"deleteWhere"),g.deleteMany(l,a)},async findFirst(e,n){const{baseWhere:a}=c(e);return f(e).findFirst(e,{...E(n),baseWhere:b(n?.baseWhere,a),relationBaseWhere:y})},async findFirstOrThrow(e,n){const{baseWhere:a}=c(e);return f(e).findFirstOrThrow(e,{...E(n),baseWhere:b(n?.baseWhere,a),relationBaseWhere:y})},async findMany(e,n){const{baseWhere:a}=c(e);return f(e).findMany(e,{...E(n),baseWhere:b(n?.baseWhere,a),relationBaseWhere:y})},async get(e,n){const a=await v(e,n);if(!a.row)return null;if(a.tableName===void 0)return t.get(e,n);const{baseWhere:o,restricts:l}=c(a.tableName);if(!l)return t.get(e,n);if(!o)return a.row;const d=await r.findFirst(a.tableName,{baseWhere:o,limit:1,where:{_id:e}});return d?._id===e?d:null},async insert(e,n){const a=s.get(e);if(a){if(!M(a,"insert",{...i,row:n}))throw new p("FORBIDDEN",`insert on "${e}" denied by policy`);return r.insert(e,n)}return t.insert(e,n)},async insertMany(e,n,a){N(n.length,a?.limit,"insertMany");const o=s.get(e);if(o){for(const l of n)if(!M(o,"insert",{...i,row:l}))throw new p("FORBIDDEN",`insert on "${e}" denied by policy`);return r.insertMany(e,n,a)}return t.insertMany(e,n,a)},async insertManyUnsafe(e,n,a){N(n.length,a?.limit,"insertManyUnsafe");const o=s.get(e);if(o){for(const l of n)if(!M(o,"insert",{...i,row:l}))throw new p("FORBIDDEN",`insert on "${e}" denied by policy`);return r.insertManyUnsafe(e,n,a)}return t.insertManyUnsafe(e,n,a)},patch:(e,n,a)=>w(e,"update",o=>o.patch(e,n,a),o=>({...o,...n}),a),async patchMany(e,n,a){N(e.length,n?.limit,"patchMany");for(const o of e)await w(o.id,"update",l=>l.patch(o.id,o.patch,a),l=>({...l,...o.patch}),a);return{patched:e.length}},async patchWhere(e,n,a){const{baseWhere:o}=c(e),l=(await f(e).findMany(e,{baseWhere:b(n.where,o),relationBaseWhere:y})).page.map(d=>({id:String(d._id),patch:n.patch}));return N(l.length,a?.limit,"patchWhere"),g.patchMany(l,a)},query(e){const{baseWhere:n}=c(e),a=f(e).query(e);return n?a.filter(o=>k(o,n)):a},restore:(e,n)=>w(e,"update",async a=>{const o=a.restore??r.restore;if(!o)throw new p("BAD_REQUEST","restore is not supported by this writer");await o(e,n)},void 0,n),replace:(e,n,a)=>w(e,"update",o=>o.replace(e,n,a),o=>({...n,_creationTime:n._creationTime??o._creationTime,_id:o._id}),a),aggregate(e,n){const{baseWhere:a}=c(e);return f(e).aggregate(e,{...n,baseWhere:b(n.baseWhere,a),relationBaseWhere:y})},groupBy(e,n){const{baseWhere:a}=c(e);return f(e).groupBy(e,{...n,baseWhere:b(n.baseWhere,a),relationBaseWhere:y})},rank(e,n,a){const o=W(e,"rank");return f(e).rank(e,n,{...a,baseWhere:b(a.baseWhere,o)})},rankPage(e,n,a){const o=W(e,"rankPage");return f(e).rankPage(e,n,{...a,baseWhere:b(a?.baseWhere,o)})},wipeShard(){throw new p("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})},...O?{rankBefore:(e,n,a)=>(W(e,"rankBefore"),(f(e).rankBefore??O)(e,n,a))}:{}},A=g;for(const e of s.keys())ne(t[e])&&(A[e]=P(g,e));return g},T=t=>typeof t=="string"?t:t.name,se=t=>{const r=new Map;for(const s of t??[])r.set(s.name,new Set((s.permissions??[]).map(i=>T(i))));return r},ue=(t,r={})=>{const s=$(t),i=se(r.roles);return U(async({ctx:u,next:c})=>{const f=u.auth??{},y=await f.getIdentity?.()??null,v=f.roles??[],B=new Set;for(const n of v)for(const a of i.get(n)??[])B.add(a);const w={auth:{can:n=>B.has(T(n)),identity:y,roles:v,userId:f.userId??null},ctx:u},W=u.db,O=W[C]??W,g=ae(W,O,s,w),A={db:g},{orm:e}=u;return e!==null&&typeof e=="object"&&(A.orm=x(g)),c({ctx:A})},{policies:t,roles:r.roles??[]})};export{q as computeReadBaseWhere,M as evaluateWrite,se as indexRolePermissions,k as matchesWhere,T as permissionName,ue as rls};
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"@lunora/errors";const m=async(a,l,s)=>{let o=-1;const c=async(r,t)=>{if(r<=o)throw new i("INTERNAL","middleware next() called multiple times");o=r;const e=a[r];return e?await e({ctx:t,next:(n=>c(r+1,n?.ctx?{...t,...n.ctx}:t))}):s(t)};return c(0,l)};export{m as l};
@@ -0,0 +1 @@
1
+ import{LunoraError as S}from"./LunoraError-LVhdU0Lo.mjs";const b=t=>typeof t=="string"?t:t.name,v=(t=[])=>{const e=new Map;for(const s of t){const a=new Set;for(const i of s.permissions??[])a.add(b(i));e.set(s.name,a)}return e},N=(t,e)=>t===void 0||e.startsWith(t),R=t=>{const e=t[1],s=typeof e=="object"&&e!==null?e.method:void 0;return typeof s=="string"&&s.toUpperCase()==="PUT"?"write":"read"},$=[["delete","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",R],["getUrl","read"],["store","write"]],E=(t,e={})=>{const s=v(e.roles);return async({ctx:a,next:i})=>{const l=a.auth??{},h=await l.getIdentity?.()??null,g=l.roles??[],y=new Set;for(const o of g)for(const r of s.get(o)??[])y.add(r);const k={can:o=>y.has(b(o)),identity:h,roles:g,userId:l.userId??null},x=(o,r,c)=>{const f=t.filter(n=>n.on===o&&n.bucket===c);if(f.length===0)return;const u={auth:k,ctx:a,key:r};if(!f.some(n=>N(n.prefix,r)&&n.when(u)===!0))throw new S("FORBIDDEN",`storage ${o} on "${r}" in bucket "${c}" denied by access rule`)},p=o=>{const r=o.bucketName??"default",c={bucketName:r};for(const[u,n]of $){const m=o[u];typeof m=="function"&&(c[u]=(...d)=>{const U=typeof d[0]=="string"?d[0]:"",I=typeof n=="function"?n(d):n;return x(I,U,r),m(...d)})}const{bucket:f}=o;return typeof f=="function"&&(c.bucket=u=>p(f(u))),c},w=a.storage;return w===void 0?i():i({ctx:{storage:p(w)}})}};export{E 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&lt;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, Permission as b, RlsOptions 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&lt;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, Permission as b, RlsOptions as c, PolicyContext as d, PolicyDecision as e, PolicyDecisionOf as f };
@@ -1,11 +1,11 @@
1
- import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-DmvyEMD6.mjs";
1
+ import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-C4CMJK8x.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
- * 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
- */
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
- * 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
- */
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
- * 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
- */
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 };
@@ -1,11 +1,11 @@
1
- import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-BDY0FYHK.js";
1
+ import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-DdYF8E18.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
- * 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
- */
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
- * 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
- */
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
- * 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
- */
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 };
@@ -1,49 +1 @@
1
- import { indexRolePermissions, computeReadBaseWhere, matchesWhere, evaluateWrite, permissionName } from '../packem_shared/rls-Bi9HiyDC.mjs';
2
-
3
- const expectPolicy = (policies, options = {}) => {
4
- const rolePermissions = indexRolePermissions(options.roles);
5
- const context = options.ctx ?? {};
6
- return {
7
- as: (identity) => {
8
- const auth = identity ?? {};
9
- const roles = auth.roles ?? [];
10
- const granted = /* @__PURE__ */ new Set();
11
- for (const roleName of roles) {
12
- for (const name of rolePermissions.get(roleName) ?? []) {
13
- granted.add(name);
14
- }
15
- }
16
- const baseContext = {
17
- auth: {
18
- can: (permission) => granted.has(permissionName(permission)),
19
- // eslint-disable-next-line unicorn/no-null -- PolicyContext.auth.identity is a public `… | null` type, mirroring the middleware
20
- identity: auth.identity ?? null,
21
- roles,
22
- // eslint-disable-next-line unicorn/no-null -- PolicyContext.auth.userId is a public `null | string` type, mirroring the middleware
23
- userId: auth.userId ?? null
24
- },
25
- ctx: context
26
- };
27
- const can = (op, table, row, nextRow) => {
28
- const tablePolicies = policies.filter((policy) => policy.table === table);
29
- if (tablePolicies.length === 0) {
30
- return true;
31
- }
32
- if (op === "read") {
33
- if (!tablePolicies.some((policy) => policy.on === "read")) {
34
- return true;
35
- }
36
- const baseWhere = computeReadBaseWhere(tablePolicies, baseContext);
37
- return baseWhere === void 0 || matchesWhere(row ?? {}, baseWhere);
38
- }
39
- return evaluateWrite(tablePolicies, op, { ...baseContext, row }, nextRow);
40
- };
41
- return {
42
- can,
43
- cannot: (op, table, row, nextRow) => !can(op, table, row, nextRow)
44
- };
45
- }
46
- };
47
- };
48
-
49
- export { expectPolicy };
1
+ import{indexRolePermissions as y,computeReadBaseWhere as I,matchesWhere as P,evaluateWrite as W,permissionName as g}from"../packem_shared/rls-_iVsPvhX.mjs";const w=(f,i={})=>{const m=y(i.roles),h=i.ctx??{};return{as:p=>{const s=p??{},c=s.roles??[],u=new Set;for(const e of c)for(const t of m.get(e)??[])u.add(t);const l={auth:{can:e=>u.has(g(e)),identity:s.identity??null,roles:c,userId:s.userId??null},ctx:h},d=(e,t,r,a)=>{const n=f.filter(o=>o.table===t);if(n.length===0)return!0;if(e==="read"){if(!n.some(x=>x.on==="read"))return!0;const o=I(n,l);return o===void 0||P(r??{},o)}return W(n,e,{...l,row:r},a)};return{can:d,cannot:(e,t,r,a)=>!d(e,t,r,a)}}}};export{w as expectPolicy};