@inixiative/transitions 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,9 +3,9 @@
3
3
  A small, **stateless** primitive on top of [`@inixiative/json-rules`](https://github.com/inixiative/json-rules)
4
4
  that answers two questions about an entity's lifecycle, declaratively:
5
5
 
6
- - **"Can this change happen?"** — guard a proposed update (`check`).
7
- - **"What changes can happen?"** — list available verbs for a record (`available`), and via
8
- `toPrisma`, every record currently eligible for a verb (`eligible`).
6
+ - **"Can this change happen?"** — guard a proposed update (`checkTransition`).
7
+ - **"What changes can happen?"** — list available actions for a record (`available`), and via
8
+ `toPrisma`, every record currently eligible for an action (`eligible`).
9
9
 
10
10
  It is **not** a state machine (no statecharts/actors/hierarchy), does **not** own state, and does
11
11
  **not** execute the change or run side effects. It is a guard + affordance layer. A transition is
@@ -17,45 +17,65 @@ no deploy to change a lifecycle).
17
17
  ## Model
18
18
 
19
19
  ```
20
- model → verb → Action { paths: Transition[], permission?, label? }
21
- Transition { from: Side, to: Side & { merge? } }
22
- Side { predicate, permission?, requires? }
20
+ resource → action → Action { paths: Transition[], label? }
21
+ Transition { from: Side, to: Side & { merge? } }
22
+ Side { predicate, permission?, requires? }
23
23
  ```
24
24
 
25
+ A `resource` key is map-qualified (`map:Model`, e.g. `db:Inquiry`) — the same convention
26
+ `@inixiative/permissions` uses, so a transition's `permission` can delegate into the rebac schema.
27
+
25
28
  A `Transition` is one atomic `from → to` edge. An **Action** (a named verb) is the OR of its edges —
26
29
  disjunction lives at the action level, never inside a `Transition`, so the kernel stays atomic and
27
30
  serializable.
28
31
 
29
32
  The `from`/`to` asymmetry is load-bearing and applies to **both** `predicate` (legality) and
30
33
  `permission` (authz): `from.*` is evaluated against the **current** record, `to.*` against the
31
- **resulting (merged)** record.
34
+ **resulting (merged)** record. Permission only ever lives on a side — every authz check reads a
35
+ concrete record, so there is no record-free action-level permission.
32
36
 
33
- ## Two failure modes, one check
37
+ ## Check
34
38
 
35
39
  ```ts
36
40
  import { checkTransition } from '@inixiative/transitions';
37
41
 
38
- const approve = {
39
- from: { predicate: { field: 'status', operator: 'equals', value: 'pending' } },
40
- to: { predicate: { field: 'status', operator: 'equals', value: 'approved' } },
42
+ const rules = {
43
+ 'db:Inquiry': {
44
+ approve: {
45
+ paths: [
46
+ {
47
+ from: { predicate: { field: 'status', operator: 'equals', value: 'pending' } },
48
+ to: { predicate: { field: 'status', operator: 'equals', value: 'approved' } },
49
+ },
50
+ ],
51
+ },
52
+ },
41
53
  };
42
54
 
43
- checkTransition(approve, { status: 'pending' }, { status: 'approved' });
44
- // → { ok: true, path: approve }
55
+ checkTransition(rules, 'db:Inquiry', 'approve', { status: 'pending' }, { status: 'approved' });
56
+ // → true
45
57
 
46
- checkTransition(approve, { status: 'approved' }, { status: 'approved' });
47
- // → { ok: false, reason: { kind: 'no-from', from: 'status must equal "pending"' } }
58
+ checkTransition(rules, 'db:Inquiry', 'approve', { status: 'approved' }, { status: 'approved' });
59
+ // → { paths: [{ from: { predicate: 'status must equal "pending"' } }] }
48
60
  ```
49
61
 
50
- `check` returns a **structured reason**, never a bare bool:
62
+ `checkTransition(rules, resource, action, record, changes, { actor, authorize })` returns **`true`** when
63
+ allowed, else a structured **`Reason`** — never a bare bool:
64
+
65
+ ```ts
66
+ type SideReason = { predicate?: string; permission?: string }; // why one side failed
67
+ type PathReason = { from?: SideReason; to?: SideReason }; // why one candidate path failed
68
+ type Reason = { paths: PathReason[] }; // one entry per path tried
69
+ ```
51
70
 
52
- | `reason.kind` | meaning | suggested HTTP |
53
- | -------------- | -------------------------------------------------- | -------------- |
54
- | `no-from` | no edge starts from the current state | 409 |
55
- | `no-to` | the merged state is not a valid target | 409 |
56
- | `unauthorized` | a legal edge exists but a permission denied | 403 |
71
+ Each side reports its `predicate` (legality) and `permission` (authz) failures independently, and
72
+ `from`/`to` are kept separate — so the caller sees the whole picture, not just the first failure. To
73
+ map to HTTP: a path that fails purely on `permission` is a 403; any `predicate` failure is a 409.
74
+ `describe(reason)` builds a human-readable message.
57
75
 
58
- `describe(reason)` builds a human-readable message; `reason.kind` drives the status code.
76
+ `checkPath(transition, record, changes, options)` is the single-edge kernel underneath, returning
77
+ `true | PathReason`; `checkTransition` walks an action's paths with it and returns the first `true`,
78
+ else every path's `PathReason`.
59
79
 
60
80
  ## Permissions are injected (the seam)
61
81
 
@@ -64,38 +84,39 @@ The kernel never imports an authorization library. Per-side `permission` is a se
64
84
  `authorize` callback to evaluate it:
65
85
 
66
86
  ```ts
67
- import { check, createRebac } from '@inixiative/transitions';
87
+ import { checkTransition, createRebac } from '@inixiative/transitions';
68
88
 
69
- const authorize = createRebac({ schema: rebacSchema })('inquiry');
70
- check(transitions, 'inquiry', 'approve', record, changes, { actor, authorize });
89
+ const authorize = createRebac({ schema: rebacSchema })('db:Inquiry');
90
+ checkTransition(rules, 'db:Inquiry', 'approve', record, changes, { actor, authorize });
71
91
  ```
72
92
 
73
- Effective authz ANDs three rules, each against the record it reads:
93
+ Effective authz ANDs the two side rules, each against the record it reads:
74
94
 
75
95
  ```
76
- action.permission AND from.permission AND to.permission
77
- (verb capability) (current record) (merged record)
96
+ from.permission AND to.permission
97
+ (current record) (merged record)
78
98
  ```
79
99
 
80
- Absent = open; `null` = terminal deny.
100
+ Absent = open; `null` = terminal deny. Omit `authorize` to check legality only.
81
101
 
82
102
  ### `createRebac` / `makeRebacAuthorize` — reference implementation
83
103
 
84
104
  This package ships a **reference** rebac evaluator (`string` delegation, relation walk with cycle
85
105
  detection, `{ self }`, json-rules `{ rule }`, `any`/`all`, per-row `permissionRules` override). It's
86
- one implementation of the `Authorize` seam, kept deliberately swappable. It is slated to graduate
87
- into a standalone `@inixiative/permissions` package — when it does, inject that instead; nothing in
88
- the transition core changes.
106
+ one implementation of the `Authorize` seam, kept deliberately swappable. The standalone
107
+ [`@inixiative/permissions`](https://github.com/inixiative/permissions) package is the production
108
+ evaluator — inject its `check` as the `authorize` seam (it speaks the same map-qualified
109
+ `resource` keys); nothing in the transition core changes.
89
110
 
90
111
  ## Affordance + set query
91
112
 
92
113
  ```ts
93
114
  import { available, eligible } from '@inixiative/transitions';
94
115
 
95
- available(transitions, 'inquiry', record, { actor, authorize });
96
- // → ['approve', 'reject', 'cancel'] (from-side only — `to` needs proposed changes, so it defers to check)
116
+ available(rules, 'db:Inquiry', record, { actor, authorize });
117
+ // → ['approve', 'reject', 'cancel'] (from-side only — `to` needs proposed changes, so it defers to checkTransition)
97
118
 
98
- eligible(transitions, 'inquiry', 'approve');
119
+ eligible(rules, 'db:Inquiry', 'approve');
99
120
  // → { OR: [{ status: { equals: 'pending' } }] } (Prisma where for "every record eligible for approve")
100
121
  ```
101
122
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var jsonRules=require('@inixiative/json-rules'),lodashEs=require('lodash-es');var y=e=>Array.isArray(e)?e:e===void 0?[]:[e],O=(e,t)=>Array.isArray(t)?t:void 0,l=e=>typeof e!="function",k=(e,t,n={})=>{if(typeof e=="function")return e(t,n);let i=e??"spread";if(i==="spread")return {...t,...n};if(i==="deepMerge")return lodashEs.mergeWith(lodashEs.cloneDeep(t),lodashEs.cloneDeep(n),O);let{kind:o,path:s}=i,r=lodashEs.cloneDeep({...t,...n}),p=[...y(lodashEs.get(t,s)),...y(lodashEs.get(n,s))];return lodashEs.set(r,s,o==="appendUnique"?lodashEs.uniqWith(p,lodashEs.isEqual):p),r};var A=e=>typeof e=="string"?e:"predicate not satisfied",d=(e,t,n,i)=>!e||t===void 0?false:!e(t,n,i),b=(e,t,n={},i={})=>{let{actor:o,authorize:s,basePermission:r}=i,p=k(e.to.merge,t,n),a=jsonRules.check(e.from.predicate,t);if(a!==true)return {ok:false,reason:{kind:"no-from",from:A(a)}};let u=jsonRules.check(e.to.predicate,p);return u!==true?{ok:false,reason:{kind:"no-to",to:A(u)}}:d(s,r,t,o)?{ok:false,reason:{kind:"unauthorized",authz:"action"}}:d(s,e.from.permission,t,o)?{ok:false,reason:{kind:"unauthorized",authz:"from"}}:d(s,e.to.permission,p,o)?{ok:false,reason:{kind:"unauthorized",authz:"to"}}:{ok:true,path:e}};var Y=e=>{switch(e.kind){case "no-from":return e.from??"transition is not available from the current state";case "no-to":return e.to??"the resulting state is not a valid target";case "unauthorized":return e.authz?`not authorized (${e.authz}-level permission denied)`:"not authorized";default:return e.kind}};var c=(e,t,n,i,o,s)=>{if(e.isSuperadmin?.(i))return true;if(o===null)return false;if(typeof o=="string"){let r=e.schema[t]?.actions[o]??null,a=n.permissionRules?.[o];return c(e,t,n,i,a!==void 0?{any:[r,a]}:r,s)}if("rel"in o&&"action"in o){let r=o.rel.split("."),p=n,a=t;for(let f of r){let g=p[f];if(!g)return false;a=e.resolveModel?e.resolveModel(a,f):f,p=g;}let u=`${a}:${String(p.id)}:${o.action}`;if(s.has(u))throw new Error(`Cycle detected in permission graph: ${u}`);return s.add(u),c(e,a,p,i,o.action,s)}if("self"in o){let r=i?.id??null;return r!==null&&n[o.self]===r}return "rule"in o?jsonRules.check(o.rule,n)===true:"any"in o?o.any.some(r=>c(e,t,n,i,r,new Set(s))):"all"in o?o.all.every(r=>c(e,t,n,i,r,new Set(s))):false},C=e=>{let{model:t,...n}=e;return (i,o,s)=>c(n,t,o,s,i,new Set)},H=e=>t=>C({...e,model:t});var z=(e,t,n)=>{let i=e[t]?.[n];if(!i)throw new Error(`transition: no action "${n}" registered on model "${t}"`);return i},E=e=>{let t=e.map(({kind:r,paths:p,...a})=>a),n=r=>e.find(p=>p.kind===r),i=n("unauthorized")??n("no-to")??n("no-from");if(!i)return {kind:"no-from",paths:t};let{paths:o,...s}=i;return {...s,paths:t}},te=(e,t,n,i,o={},s={})=>{let r=z(e,t,n),p={...s,basePermission:r.permission},a=[];for(let u of r.paths){let f=b(u,i,o,p);if(f.ok)return f;a.push(f.reason);}return {ok:false,reason:E(a)}},ne=(e,t,n,i={})=>{let o=e[t];if(!o)return [];let{actor:s,authorize:r}=i,p=(a,u)=>!r||a===void 0||r(a,u,s);return Object.entries(o).filter(([,a])=>a.paths.some(u=>jsonRules.check(u.from.predicate,n)===true&&p(a.permission,n)&&p(u.from.permission,n))).map(([a])=>a)},oe=(e,t,n)=>{let i=z(e,t,n),{steps:o}=jsonRules.toPrisma({any:i.paths.map(r=>r.from.predicate)}),s=o[o.length-1];if(s?.operation!=="where"||s.where===void 0)throw new Error("transition: expected a terminal WhereStep from toPrisma; got none");return s.where};var re=e=>l(e.to.merge);var _=new Set(["spread","deepMerge"]),L=new Set(["append","appendUnique"]),N=(e,t,n,i)=>{let o=jsonRules.validateRule(e);for(let s of o.errors)t.push({path:`${n}.${s.path}`,message:s.message});if(i){let s=jsonRules.checkRuleAgainstLens(e,i);for(let r of s.violations)t.push({path:`${n}.${r.path}`,message:r.reason});}},h=(e,t,n)=>{if(!(e==null||typeof e=="string")){if("rule"in e){let i=jsonRules.validateRule(e.rule);for(let o of i.errors)t.push({path:`${n}.rule.${o.path}`,message:o.message});return}if("rel"in e){(!e.rel||!e.action)&&t.push({path:n,message:"rel-rule requires non-empty `rel` and `action`"});return}if("self"in e){e.self||t.push({path:n,message:"self-rule requires a non-empty field name"});return}if("any"in e){e.any.forEach((i,o)=>{h(i,t,`${n}.any[${o}]`);});return}if("all"in e){e.all.forEach((i,o)=>{h(i,t,`${n}.all[${o}]`);});return}t.push({path:n,message:"unrecognized ActionRule shape"});}},W=(e,t,n)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){_.has(e)||t.push({path:n,message:`unknown merge strategy "${e}"`});return}L.has(e.kind)?e.path||t.push({path:n,message:`merge "${e.kind}" requires a \`path\``}):t.push({path:n,message:`unknown merge kind "${e.kind}"`});}},S=(e,t,n,i)=>{N(e.predicate,t,`${n}.predicate`,i.lens),h(e.permission,t,`${n}.permission`),e.requires!==void 0&&(typeof e.requires!="object"||e.requires===null)&&t.push({path:`${n}.requires`,message:"`requires` must be a Prisma-include-shaped object"}),"merge"in e&&W(e.merge,t,`${n}.merge`);},fe=(e,t={})=>{let n=[];return S(e.from,n,"from",t),S(e.to,n,"to",t),t.requireSerializable&&!l(e.to.merge)&&n.push({path:"to.merge",message:"callback merge is not serializable; use a keyword strategy"}),{ok:n.length===0,errors:n}};exports.applyMerge=k;exports.available=ne;exports.check=te;exports.checkTransition=b;exports.createRebac=H;exports.describe=Y;exports.eligible=oe;exports.isSerializable=re;exports.isSerializableMerge=l;exports.makeRebacAuthorize=C;exports.validateTransition=fe;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var jsonRules=require('@inixiative/json-rules'),lodashEs=require('lodash-es');var h=e=>Array.isArray(e)?e:e===void 0?[]:[e],O=(e,t)=>Array.isArray(t)?t:void 0,m=e=>typeof e!="function",y=(e,t,n={})=>{if(typeof e=="function")return e(t,n);let i=e??"spread";if(i==="spread")return {...t,...n};if(i==="deepMerge")return lodashEs.mergeWith(lodashEs.cloneDeep(t),lodashEs.cloneDeep(n),O);let{kind:o,path:r}=i,s=lodashEs.cloneDeep({...t,...n}),a=[...h(lodashEs.get(t,r)),...h(lodashEs.get(n,r))];return lodashEs.set(s,r,o==="appendUnique"?lodashEs.uniqWith(a,lodashEs.isEqual):a),s};var A=e=>typeof e=="string"?e:"predicate not satisfied",b=(e,t,n,i)=>!e||t===void 0?false:!e(t,n,i),k=(e,t,n={},i={})=>{let{actor:o,authorize:r}=i,s=y(e.to.merge,t,n),a={},p=jsonRules.check(e.from.predicate,t);p!==true&&(a.predicate=A(p)),b(r,e.from.permission,t,o)&&(a.permission="not authorized");let f={},c=jsonRules.check(e.to.predicate,s);c!==true&&(f.predicate=A(c)),b(r,e.to.permission,s,o)&&(f.permission="not authorized");let u={};return (a.predicate||a.permission)&&(u.from=a),(f.predicate||f.permission)&&(u.to=f),u.from||u.to?u:true};var S=e=>{let t=[];return e.from?.predicate&&t.push(`from: ${e.from.predicate}`),e.from?.permission&&t.push(`from: ${e.from.permission}`),e.to?.predicate&&t.push(`to: ${e.to.predicate}`),e.to?.permission&&t.push(`to: ${e.to.permission}`),t.join("; ")||"unknown"},G=e=>e.paths.length===0?"no transition path available":e.paths.length===1?S(e.paths[0]):e.paths.map((t,n)=>`path ${n}: ${S(t)}`).join(" | ");var l=(e,t,n,i,o,r)=>{if(e.isSuperadmin?.(i))return true;if(o===null)return false;if(typeof o=="string"){let s=e.schema[t]?.actions[o]??null,p=n.permissionRules?.[o];return l(e,t,n,i,p!==void 0?{any:[s,p]}:s,r)}if("rel"in o&&"action"in o){let s=o.rel.split("."),a=n,p=t;for(let c of s){let u=a[c];if(!u)return false;p=e.resolveModel?e.resolveModel(p,c):c,a=u;}let f=`${p}:${String(a.id)}:${o.action}`;if(r.has(f))throw new Error(`Cycle detected in permission graph: ${f}`);return r.add(f),l(e,p,a,i,o.action,r)}if("self"in o){let s=i?.id??null;return s!==null&&n[o.self]===s}return "rule"in o?jsonRules.check(o.rule,n)===true:"any"in o?o.any.some(s=>l(e,t,n,i,s,new Set(r))):"all"in o?o.all.every(s=>l(e,t,n,i,s,new Set(r))):false},v=e=>{let{model:t,...n}=e;return (i,o,r)=>l(n,t,o,r,i,new Set)},H=e=>t=>v({...e,model:t});var $=(e,t,n)=>{let i=e[t]?.[n];if(!i)throw new Error(`transition: no action "${n}" registered on resource "${t}"`);return i},te=(e,t,n,i,o={},r={})=>{let s=$(e,t,n),a=[];for(let p of s.paths){let f=k(p,i,o,r);if(f===true)return true;a.push(f);}return {paths:a}},ne=(e,t,n,i={})=>{let o=e[t];if(!o)return [];let{actor:r,authorize:s}=i,a=(p,f)=>!s||p===void 0||s(p,f,r);return Object.entries(o).filter(([,p])=>p.paths.some(f=>jsonRules.check(f.from.predicate,n)===true&&a(f.from.permission,n))).map(([p])=>p)},oe=(e,t,n)=>{let i=$(e,t,n),{steps:o}=jsonRules.toPrisma({any:i.paths.map(s=>s.from.predicate)}),r=o[o.length-1];if(r?.operation!=="where"||r.where===void 0)throw new Error("transition: expected a terminal WhereStep from toPrisma; got none");return r.where};var se=e=>m(e.to.merge);var L=new Set(["spread","deepMerge"]),j=new Set(["append","appendUnique"]),N=(e,t,n,i)=>{let o=jsonRules.validateRule(e);for(let r of o.errors)t.push({path:`${n}.${r.path}`,message:r.message});if(i){let r=jsonRules.checkRuleAgainstLens(e,i);for(let s of r.violations)t.push({path:`${n}.${s.path}`,message:s.reason});}},g=(e,t,n)=>{if(!(e==null||typeof e=="string")){if("rule"in e){let i=jsonRules.validateRule(e.rule);for(let o of i.errors)t.push({path:`${n}.rule.${o.path}`,message:o.message});return}if("rel"in e){(!e.rel||!e.action)&&t.push({path:n,message:"rel-rule requires non-empty `rel` and `action`"});return}if("self"in e){e.self||t.push({path:n,message:"self-rule requires a non-empty field name"});return}if("any"in e){e.any.forEach((i,o)=>{g(i,t,`${n}.any[${o}]`);});return}if("all"in e){e.all.forEach((i,o)=>{g(i,t,`${n}.all[${o}]`);});return}t.push({path:n,message:"unrecognized ActionRule shape"});}},W=(e,t,n)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){L.has(e)||t.push({path:n,message:`unknown merge strategy "${e}"`});return}j.has(e.kind)?e.path||t.push({path:n,message:`merge "${e.kind}" requires a \`path\``}):t.push({path:n,message:`unknown merge kind "${e.kind}"`});}},M=(e,t,n,i)=>{N(e.predicate,t,`${n}.predicate`,i.lens),g(e.permission,t,`${n}.permission`),e.requires!==void 0&&(typeof e.requires!="object"||e.requires===null)&&t.push({path:`${n}.requires`,message:"`requires` must be a Prisma-include-shaped object"}),"merge"in e&&W(e.merge,t,`${n}.merge`);},ue=(e,t={})=>{let n=[];return M(e.from,n,"from",t),M(e.to,n,"to",t),t.requireSerializable&&!m(e.to.merge)&&n.push({path:"to.merge",message:"callback merge is not serializable; use a keyword strategy"}),{ok:n.length===0,errors:n}};exports.applyMerge=y;exports.available=ne;exports.checkPath=k;exports.checkTransition=te;exports.createRebac=H;exports.describe=G;exports.eligible=oe;exports.isSerializable=se;exports.isSerializableMerge=m;exports.makeRebacAuthorize=v;exports.validateTransition=ue;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/merge.ts","../src/check.ts","../src/describe.ts","../src/rebac/authorize.ts","../src/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["toArray","value","replaceArrays","_target","source","isSerializableMerge","merge","applyMerge","record","changes","strategy","mergeWith","cloneDeep","kind","path","base","merged","get","set","uniqWith","isEqual","reasonString","result","denies","authorize","rule","actor","checkTransition","transition","options","basePermission","next","fromResult","checkRule","toResult","describe","reason","evaluate","ctx","model","visited","schemaRule","rowRule","segments","current","currentModel","segment","related","key","actorId","sub","makeRebacAuthorize","rest","createRebac","getAction","map","verb","action","aggregate","failures","paths","_kind","_paths","pick","failure","chosen","_omit","representative","check","opts","available","actions","allows","rec","eligible","steps","toPrisma","last","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","predicate","errors","lens","validateRule","issue","lensCheck","checkRuleAgainstLens","violation","validatePermission","i","validateMerge","validateSide","side","validateTransition"],"mappings":"2FAGA,IAAMA,CAAAA,CAAWC,CAAAA,EACf,MAAM,OAAA,CAAQA,CAAK,CAAA,CAAIA,CAAAA,CAAQA,IAAU,MAAA,CAAY,EAAC,CAAI,CAACA,CAAK,CAAA,CAG5DC,CAAAA,CAAgB,CAACC,CAAAA,CAAkBC,IACvC,KAAA,CAAM,OAAA,CAAQA,CAAM,CAAA,CAAIA,EAAS,MAAA,CAGtBC,CAAAA,CAAuBC,CAAAA,EAA2B,OAAOA,GAAU,UAAA,CAWnEC,CAAAA,CAAa,CACxBD,CAAAA,CACAE,EACAC,CAAAA,CAAsB,EAAC,GACjB,CACN,GAAI,OAAOH,CAAAA,EAAU,UAAA,CAAY,OAAOA,EAAME,CAAAA,CAAQC,CAAO,CAAA,CAE7D,IAAMC,EAA0BJ,CAAAA,EAAS,QAAA,CAEzC,GAAII,CAAAA,GAAa,SAAU,OAAO,CAAE,GAAGF,CAAAA,CAAQ,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cesContent":["import { cloneDeep, get, isEqual, mergeWith, set, uniqWith } from 'lodash-es';\nimport type { Merge, MergeStrategy, Row } from './types';\n\nconst toArray = (value: unknown): unknown[] =>\n Array.isArray(value) ? value : value === undefined ? [] : [value];\n\n// deepMerge replaces arrays wholesale rather than index-merging them (the intuitive default).\nconst replaceArrays = (_target: unknown, source: unknown): unknown[] | undefined =>\n Array.isArray(source) ? source : undefined;\n\n/** A transition is persistable iff its merge is absent or a keyword strategy (callbacks are not). */\nexport const isSerializableMerge = (merge?: Merge): boolean => typeof merge !== 'function';\n\n/**\n * Produce the resulting record from a current record + proposed changes.\n *\n * - `spread` (default) — shallow overwrite (`{ ...record, ...changes }`)\n * - `deepMerge` — recursive object merge, arrays replaced\n * - `{ kind: 'append', path }` — concat `changes[path]` onto `record[path]`\n * - `{ kind: 'appendUnique', path }` — append + dedupe (deep equality)\n * - a callback — full power, not serializable\n */\nexport const applyMerge = <R extends Row>(\n merge: Merge<R> | undefined,\n record: R,\n changes: Partial<R> = {},\n): R => {\n if (typeof merge === 'function') return merge(record, changes);\n\n const strategy: MergeStrategy = merge ?? 'spread';\n\n if (strategy === 'spread') return { ...record, ...changes };\n // clone BOTH inputs: mergeWith assigns nested objects/arrays from `changes` by reference, which\n // would alias the caller's `changes` into the returned record (a mutation footgun for a pure guard).\n if (strategy === 'deepMerge')\n return mergeWith(cloneDeep(record), cloneDeep(changes), replaceArrays);\n\n // field-scoped array strategies: spread the rest of `changes`, then concat at `path`.\n const { kind, path } = strategy;\n const base = cloneDeep({ ...record, ...changes }) as R;\n const merged = [...toArray(get(record, path)), ...toArray(get(changes, path))];\n set(base as Row, path, kind === 'appendUnique' ? uniqWith(merged, isEqual) : merged);\n return base;\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport { applyMerge } from './merge';\nimport type {\n ActionRule,\n Actor,\n Authorize,\n CheckOptions,\n CheckResult,\n Row,\n Transition,\n} from './types';\n\nconst reasonString = (result: boolean | string): string =>\n typeof result === 'string' ? result : 'predicate not satisfied';\n\n/**\n * Does this permission DENY?\n * - no authorizer injected → can't deny (legality-only mode)\n * - `undefined` rule → permission absent → open → can't deny\n * - any other rule (incl. `null` = terminal deny) → delegate to the authorizer\n */\nconst denies = (\n authorize: Authorize | undefined,\n rule: ActionRule | undefined,\n record: Row,\n actor: Actor,\n): boolean => {\n if (!authorize || rule === undefined) return false;\n return !authorize(rule, record, actor);\n};\n\n/**\n * The kernel: evaluate one atomic transition.\n *\n * Legality (json-rules) AND authz (injected, per side), with the load-bearing asymmetry —\n * `from.*` reads the current `record`, `to.*` reads the merged `next` record. Authz order is\n * action baseline → from → to, all ANDed. Returns a structured {@link CheckResult} whose\n * `reason.kind` lets a caller map illegal → 409 vs unauthorized → 403.\n *\n * Omit `options.authorize` to check legality only.\n */\nexport const checkTransition = <R extends Row>(\n transition: Transition<R>,\n record: R,\n changes: Partial<R> = {},\n options: CheckOptions = {},\n): CheckResult<R> => {\n const { actor, authorize, basePermission } = options;\n const next = applyMerge(transition.to.merge, record, changes);\n\n const fromResult = checkRule(transition.from.predicate, record as Row);\n if (fromResult !== true)\n return { ok: false, reason: { kind: 'no-from', from: reasonString(fromResult) } };\n\n const toResult = checkRule(transition.to.predicate, next as Row);\n if (toResult !== true)\n return { ok: false, reason: { kind: 'no-to', to: reasonString(toResult) } };\n\n if (denies(authorize, basePermission, record as Row, actor))\n return { ok: false, reason: { kind: 'unauthorized', authz: 'action' } };\n if (denies(authorize, transition.from.permission, record as Row, actor))\n return { ok: false, reason: { kind: 'unauthorized', authz: 'from' } };\n if (denies(authorize, transition.to.permission, next as Row, actor))\n return { ok: false, reason: { kind: 'unauthorized', authz: 'to' } };\n\n return { ok: true, path: transition };\n};\n","import type { Reason } from './types';\n\n/** Build a human-readable message from a structured {@link Reason} (logs / UI / error bodies). */\nexport const describe = (reason: Reason): string => {\n switch (reason.kind) {\n case 'no-from':\n return reason.from ?? 'transition is not available from the current state';\n case 'no-to':\n return reason.to ?? 'the resulting state is not a valid target';\n case 'unauthorized':\n return reason.authz\n ? `not authorized (${reason.authz}-level permission denied)`\n : 'not authorized';\n default: {\n // exhaustiveness guard: a new FailureKind must be handled here, not silently return undefined\n const _exhaustive: never = reason.kind;\n return _exhaustive;\n }\n }\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport type { ActionRule, Actor, Authorize, Row } from '../types';\nimport type { RebacOptions, RebacSchema } from './types';\n\ntype Context = {\n schema: RebacSchema;\n resolveModel?: (model: string, relationSegment: string) => string;\n isSuperadmin?: (actor: Actor) => boolean;\n};\n\nconst evaluate = (\n ctx: Context,\n model: string,\n record: Row,\n actor: Actor,\n rule: ActionRule,\n visited: Set<string>,\n): boolean => {\n if (ctx.isSuperadmin?.(actor)) return true;\n if (rule === null) return false;\n\n // string → delegate to the named action on this model, additively merged with any per-row override.\n if (typeof rule === 'string') {\n const schemaRule = ctx.schema[model]?.actions[rule] ?? null;\n const rowRules = record.permissionRules as Record<string, ActionRule> | null | undefined;\n const rowRule = rowRules?.[rule];\n const merged: ActionRule = rowRule !== undefined ? { any: [schemaRule, rowRule] } : schemaRule;\n return evaluate(ctx, model, record, actor, merged, visited);\n }\n\n // { rel, action } → walk the relation (dot-paths supported), then check `action` on the target.\n if ('rel' in rule && 'action' in rule) {\n const segments = rule.rel.split('.');\n let current: Row = record;\n let currentModel = model;\n for (const segment of segments) {\n const related = current[segment] as Row | null | undefined;\n if (!related) return false;\n currentModel = ctx.resolveModel ? ctx.resolveModel(currentModel, segment) : segment;\n current = related;\n }\n const key = `${currentModel}:${String(current.id)}:${rule.action}`;\n if (visited.has(key)) throw new Error(`Cycle detected in permission graph: ${key}`);\n visited.add(key);\n return evaluate(ctx, currentModel, current, actor, rule.action, visited);\n }\n\n // { self } → record[field] matches the current actor.\n if ('self' in rule) {\n const actorId = actor?.id ?? null;\n return actorId !== null && record[rule.self] === actorId;\n }\n\n // { rule } → ABAC predicate (json-rules) over the record.\n if ('rule' in rule) return checkRule(rule.rule, record) === true;\n\n // Fork `visited` per branch — parallel paths through any/all aren't cycles.\n if ('any' in rule)\n return rule.any.some((sub) => evaluate(ctx, model, record, actor, sub, new Set(visited)));\n if ('all' in rule)\n return rule.all.every((sub) => evaluate(ctx, model, record, actor, sub, new Set(visited)));\n\n return false;\n};\n\n/**\n * A reference rebac evaluator — one implementation of the injected {@link Authorize} seam,\n * bound to a single `model`. Faithful to `@template/permissions`' `rebac/check` (string-delegate,\n * relation walk with cycle detection, self, json-rules `{ rule }`, any/all, per-row\n * `permissionRules` override) but standalone. Swap it for a richer authorizer in production;\n * this is slated to graduate into `@inixiative/permissions`.\n */\nexport const makeRebacAuthorize = (options: RebacOptions & { model: string }): Authorize => {\n const { model, ...rest } = options;\n return (rule, record, actor) => evaluate(rest, model, record, actor, rule, new Set());\n};\n\n/** Curried form: `createRebac({ schema })(model)` → an {@link Authorize} for that model. */\nexport const createRebac =\n (options: RebacOptions) =>\n (model: string): Authorize =>\n makeRebacAuthorize({ ...options, model });\n","import { check as checkRule, toPrisma } from '@inixiative/json-rules';\nimport { checkTransition } from './check';\nimport type {\n Action,\n AuthorizeOptions,\n CheckOptions,\n CheckResult,\n PathFailure,\n Reason,\n Row,\n TransitionMap,\n} from './types';\n\nconst getAction = (map: TransitionMap, model: string, verb: string): Action => {\n const action = map[model]?.[verb];\n if (!action) throw new Error(`transition: no action \"${verb}\" registered on model \"${model}\"`);\n return action;\n};\n\n// Pick the most-progressed failure across an action's paths:\n// unauthorized (a legal edge existed but authz denied) → 403\n// no-to (from matched, target invalid) → 409\n// no-from (no edge even starts here) → 409\nconst aggregate = (failures: Reason[]): Reason => {\n const paths: PathFailure[] = failures.map(({ kind: _kind, paths: _paths, ...rest }) => rest);\n const pick = (kind: Reason['kind']) => failures.find((failure) => failure.kind === kind);\n const chosen = pick('unauthorized') ?? pick('no-to') ?? pick('no-from');\n if (!chosen) return { kind: 'no-from', paths };\n const { paths: _omit, ...representative } = chosen;\n return { ...representative, paths };\n};\n\n/**\n * Authoritative check: the FIRST path whose `from` matches the current record, whose `to`\n * matches the merged record, and whose permissions all pass, wins. If none pass, returns the\n * aggregated structured failure (see {@link aggregate}).\n */\nexport const check = (\n map: TransitionMap,\n model: string,\n verb: string,\n record: Row,\n changes: Row = {},\n options: AuthorizeOptions = {},\n): CheckResult => {\n const action = getAction(map, model, verb);\n const opts: CheckOptions = { ...options, basePermission: action.permission };\n\n const failures: Reason[] = [];\n for (const path of action.paths) {\n const result = checkTransition(path, record, changes, opts);\n if (result.ok) return result;\n failures.push(result.reason);\n }\n return { ok: false, reason: aggregate(failures) };\n};\n\n/**\n * Affordance hint: which verbs are offerable from `record` right now. Evaluates ONLY the\n * `from` side (predicate + `action`/`from` permission against the current record) — `to` needs\n * the merged record, which doesn't exist without proposed changes, so it defers to {@link check}.\n */\nexport const available = (\n map: TransitionMap,\n model: string,\n record: Row,\n options: AuthorizeOptions = {},\n): string[] => {\n const actions = map[model];\n if (!actions) return [];\n const { actor, authorize } = options;\n\n const allows = (rule: Action['permission'], rec: Row): boolean =>\n !authorize || rule === undefined || authorize(rule, rec, actor);\n\n return Object.entries(actions)\n .filter(([, action]) =>\n action.paths.some(\n (path) =>\n checkRule(path.from.predicate, record) === true &&\n allows(action.permission, record) &&\n allows(path.from.permission, record),\n ),\n )\n .map(([verb]) => verb);\n};\n\n/**\n * Set query: one OR'd Prisma `where` matching every record currently eligible for `verb`\n * (the union of all its paths' `from` predicates). Empty action → match-nothing.\n */\nexport const eligible = (map: TransitionMap, model: string, verb: string): Row => {\n const action = getAction(map, model, verb);\n const { steps } = toPrisma({ any: action.paths.map((path) => path.from.predicate) });\n // json-rules guarantees the last step is the WhereStep. Assert it loudly rather than cast-and-swallow:\n // a silent `{}` fallback would mean match-EVERYTHING — the dangerous inverse of the intended\n // match-nothing — if a future json-rules emits a trailing non-where step or multi-step relation refs.\n const last = steps[steps.length - 1] as { operation?: string; where?: Row } | undefined;\n if (last?.operation !== 'where' || last.where === undefined)\n throw new Error('transition: expected a terminal WhereStep from toPrisma; got none');\n return last.where;\n};\n","import { isSerializableMerge } from './merge';\nimport type { Transition } from './types';\n\n/**\n * Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?\n *\n * Predicates (json-rules) and permissions (ActionRule) are always plain JSON; the only\n * non-data escape hatch is a `to.merge` callback. So serializability reduces to the merge.\n */\nexport const isSerializable = (transition: Transition): boolean =>\n isSerializableMerge(transition.to.merge);\n","import {\n type Condition,\n checkRuleAgainstLens,\n type Lens,\n type LensNarrowing,\n validateRule,\n} from '@inixiative/json-rules';\nimport { isSerializableMerge } from './merge';\nimport type { ActionRule, Merge, Side, ToSide, Transition } from './types';\n\nexport type ValidationIssue = { path: string; message: string };\nexport type ValidationResult = { ok: boolean; errors: ValidationIssue[] };\n\nexport type ValidateOptions = {\n /** Optional field/relation allowlist; passed through to json-rules lens validation per predicate. */\n lens?: Lens | LensNarrowing;\n /** Reject callback merges (use when the transition must be persistable / tenant-configured). */\n requireSerializable?: boolean;\n};\n\nconst MERGE_KEYWORDS = new Set(['spread', 'deepMerge']);\nconst ARRAY_KINDS = new Set(['append', 'appendUnique']);\n\nconst validatePredicate = (\n predicate: Condition,\n errors: ValidationIssue[],\n path: string,\n lens?: Lens | LensNarrowing,\n): void => {\n const result = validateRule(predicate);\n for (const issue of result.errors)\n errors.push({ path: `${path}.${issue.path}`, message: issue.message });\n if (lens) {\n const lensCheck = checkRuleAgainstLens(predicate, lens);\n for (const violation of lensCheck.violations)\n errors.push({ path: `${path}.${violation.path}`, message: violation.reason });\n }\n};\n\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined || rule === null || typeof rule === 'string') return;\n if ('rule' in rule) {\n const result = validateRule(rule.rule);\n for (const issue of result.errors)\n errors.push({ path: `${path}.rule.${issue.path}`, message: issue.message });\n return;\n }\n if ('rel' in rule) {\n if (!rule.rel || !rule.action)\n errors.push({ path, message: 'rel-rule requires non-empty `rel` and `action`' });\n return;\n }\n if ('self' in rule) {\n if (!rule.self) errors.push({ path, message: 'self-rule requires a non-empty field name' });\n return;\n }\n if ('any' in rule) {\n rule.any.forEach((sub, i) => {\n validatePermission(sub, errors, `${path}.any[${i}]`);\n });\n return;\n }\n if ('all' in rule) {\n rule.all.forEach((sub, i) => {\n validatePermission(sub, errors, `${path}.all[${i}]`);\n });\n return;\n }\n errors.push({ path, message: 'unrecognized ActionRule shape' });\n};\n\nconst validateMerge = (merge: Merge | undefined, errors: ValidationIssue[], path: string): void => {\n if (merge === undefined || typeof merge === 'function') return;\n if (typeof merge === 'string') {\n if (!MERGE_KEYWORDS.has(merge))\n errors.push({ path, message: `unknown merge strategy \"${merge}\"` });\n return;\n }\n if (!ARRAY_KINDS.has(merge.kind))\n errors.push({ path, message: `unknown merge kind \"${merge.kind}\"` });\n else if (!merge.path) errors.push({ path, message: `merge \"${merge.kind}\" requires a \\`path\\`` });\n};\n\nconst validateSide = (\n side: Side | ToSide,\n errors: ValidationIssue[],\n path: string,\n options: ValidateOptions,\n): void => {\n validatePredicate(side.predicate, errors, `${path}.predicate`, options.lens);\n validatePermission(side.permission, errors, `${path}.permission`);\n if (side.requires !== undefined && (typeof side.requires !== 'object' || side.requires === null))\n errors.push({\n path: `${path}.requires`,\n message: '`requires` must be a Prisma-include-shaped object',\n });\n if ('merge' in side) validateMerge(side.merge, errors, `${path}.merge`);\n};\n\n/**\n * Authoring validation for a single transition — run on save before persisting a tenant config.\n * Predicate validity delegates to json-rules (`validateRule`, plus `checkRuleAgainstLens` when a\n * `lens` is supplied for field/relation scoping); merge strategy and permission shape are checked here.\n */\nexport const validateTransition = (\n transition: Transition,\n options: ValidateOptions = {},\n): ValidationResult => {\n const errors: ValidationIssue[] = [];\n validateSide(transition.from, errors, 'from', options);\n validateSide(transition.to, errors, 'to', options);\n if (options.requireSerializable && !isSerializableMerge(transition.to.merge))\n errors.push({\n path: 'to.merge',\n message: 'callback merge is not serializable; use a keyword strategy',\n });\n return { ok: errors.length === 0, errors };\n};\n"]}
1
+ {"version":3,"sources":["../src/merge.ts","../src/check.ts","../src/describe.ts","../src/rebac/authorize.ts","../src/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["toArray","value","replaceArrays","_target","source","isSerializableMerge","merge","applyMerge","record","changes","strategy","mergeWith","cloneDeep","kind","path","base","merged","get","set","uniqWith","isEqual","predicateReason","result","denies","authorize","rule","actor","checkPath","transition","options","next","from","fromPredicate","checkRule","to","toPredicate","reason","describePath","segs","describe","i","evaluate","ctx","model","visited","schemaRule","rowRule","segments","current","currentModel","segment","related","key","actorId","sub","makeRebacAuthorize","rest","createRebac","getAction","rules","resource","action","found","checkTransition","paths","available","actions","allows","rec","eligible","steps","toPrisma","last","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","predicate","errors","lens","validateRule","issue","lensCheck","checkRuleAgainstLens","violation","validatePermission","validateMerge","validateSide","side","validateTransition"],"mappings":"2FAGA,IAAMA,CAAAA,CAAWC,CAAAA,EACf,KAAA,CAAM,OAAA,CAAQA,CAAK,EAAIA,CAAAA,CAAQA,CAAAA,GAAU,MAAA,CAAY,GAAK,CAACA,CAAK,CAAA,CAG5DC,CAAAA,CAAgB,CAACC,CAAAA,CAAkBC,CAAAA,GACvC,KAAA,CAAM,OAAA,CAAQA,CAAM,CAAA,CAAIA,CAAAA,CAAS,MAAA,CAGtBC,EAAuBC,CAAAA,EAA2B,OAAOA,CAAAA,EAAU,UAAA,CAWnEC,EAAa,CACxBD,CAAAA,CACAE,CAAAA,CACAC,CAAAA,CAAsB,EAAC,GACjB,CACN,GAAI,OAAOH,GAAU,UAAA,CAAY,OAAOA,CAAAA,CAAME,CAAAA,CAAQC,CAAO,CAAA,CAE7D,IAAMC,CAAAA,CAA0BJ,CAAAA,EAAS,SAEzC,GAAII,CAAAA,GAAa,QAAA,CAAU,OAAO,CAAE,GAAGF,CAAAA,CAAQ,GAAGC,CAAQ,CAAA,CAG1D,GAAIC,CAAAA,GAAa,WAAA,CACf,OAAOC,kBAAAA,CAAUC,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D,CAAAA,CAAmBG,EAAK,UAAA,CAAYV,CAAAA,CAAQ,CAAA,EAAGhE,CAAI,aAAa,CAAA,CAC5D0E,CAAAA,CAAK,QAAA,GAAa,MAAA,GAAc,OAAOA,CAAAA,CAAK,QAAA,EAAa,QAAA,EAAYA,CAAAA,CAAK,QAAA,GAAa,IAAA,CAAA,EACzFV,CAAAA,CAAO,IAAA,CAAK,CACV,IAAA,CAAM,CAAA,EAAGhE,CAAI,CAAA,SAAA,CAAA,CACb,QAAS,mDACX,CAAC,CAAA,CACC,OAAA,GAAW0E,GAAMF,CAAAA,CAAcE,CAAAA,CAAK,KAAA,CAAOV,CAAAA,CAAQ,GAAGhE,CAAI,CAAA,MAAA,CAAQ,EACxE,CAAA,CAOa2E,GAAqB,CAChC7D,CAAAA,CACAC,CAAAA,CAA2B,KACN,CACrB,IAAMiD,CAAAA,CAA4B,GAClC,OAAAS,CAAAA,CAAa3D,CAAAA,CAAW,IAAA,CAAMkD,CAAAA,CAAQ,MAAA,CAAQjD,CAAO,CAAA,CACrD0D,EAAa3D,CAAAA,CAAW,EAAA,CAAIkD,CAAAA,CAAQ,IAAA,CAAMjD,CAAO,CAAA,CAC7CA,CAAAA,CAAQ,mBAAA,EAAuB,CAACxB,EAAoBuB,CAAAA,CAAW,EAAA,CAAG,KAAK,CAAA,EACzEkD,EAAO,IAAA,CAAK,CACV,IAAA,CAAM,UAAA,CACN,QAAS,4DACX,CAAC,CAAA,CACI,CAAE,GAAIA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAAAA,CAAO,CAC3C","file":"index.cjs","sourcesContent":["import { cloneDeep, get, isEqual, mergeWith, set, uniqWith } from 'lodash-es';\nimport type { Merge, MergeStrategy, Row } from './types';\n\nconst toArray = (value: unknown): unknown[] =>\n Array.isArray(value) ? value : value === undefined ? [] : [value];\n\n// deepMerge replaces arrays wholesale rather than index-merging them (the intuitive default).\nconst replaceArrays = (_target: unknown, source: unknown): unknown[] | undefined =>\n Array.isArray(source) ? source : undefined;\n\n/** A transition is persistable iff its merge is absent or a keyword strategy (callbacks are not). */\nexport const isSerializableMerge = (merge?: Merge): boolean => typeof merge !== 'function';\n\n/**\n * Produce the resulting record from a current record + proposed changes.\n *\n * - `spread` (default) — shallow overwrite (`{ ...record, ...changes }`)\n * - `deepMerge` — recursive object merge, arrays replaced\n * - `{ kind: 'append', path }` — concat `changes[path]` onto `record[path]`\n * - `{ kind: 'appendUnique', path }` — append + dedupe (deep equality)\n * - a callback — full power, not serializable\n */\nexport const applyMerge = <R extends Row>(\n merge: Merge<R> | undefined,\n record: R,\n changes: Partial<R> = {},\n): R => {\n if (typeof merge === 'function') return merge(record, changes);\n\n const strategy: MergeStrategy = merge ?? 'spread';\n\n if (strategy === 'spread') return { ...record, ...changes };\n // clone BOTH inputs: mergeWith assigns nested objects/arrays from `changes` by reference, which\n // would alias the caller's `changes` into the returned record (a mutation footgun for a pure guard).\n if (strategy === 'deepMerge')\n return mergeWith(cloneDeep(record), cloneDeep(changes), replaceArrays);\n\n // field-scoped array strategies: spread the rest of `changes`, then concat at `path`.\n const { kind, path } = strategy;\n const base = cloneDeep({ ...record, ...changes }) as R;\n const merged = [...toArray(get(record, path)), ...toArray(get(changes, path))];\n set(base as Row, path, kind === 'appendUnique' ? uniqWith(merged, isEqual) : merged);\n return base;\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport { applyMerge } from './merge';\nimport type {\n ActionRule,\n Actor,\n Authorize,\n AuthorizeOptions,\n PathReason,\n Row,\n SideReason,\n Transition,\n} from './types';\n\nconst predicateReason = (result: boolean | string): string =>\n typeof result === 'string' ? result : 'predicate not satisfied';\n\n/**\n * Does this permission DENY?\n * - no authorizer injected → can't deny (legality-only mode)\n * - `undefined` rule → permission absent → open → can't deny\n * - any other rule (incl. `null` = terminal deny) → delegate to the authorizer\n */\nconst denies = (\n authorize: Authorize | undefined,\n rule: ActionRule | undefined,\n record: Row,\n actor: Actor,\n): boolean => {\n if (!authorize || rule === undefined) return false;\n return !authorize(rule, record, actor);\n};\n\n/**\n * The kernel: evaluate one atomic edge. Reports every failure rather than short-circuiting —\n * `from`/`to` and predicate/permission are independent slots — so a caller sees the whole\n * picture. `from.*` reads the current `record`, `to.*` reads the merged `next` record. Returns\n * `true` when the edge is allowed, else the {@link PathReason}. Omit `authorize` for legality only.\n */\nexport const checkPath = <R extends Row>(\n transition: Transition<R>,\n record: R,\n changes: Partial<R> = {},\n options: AuthorizeOptions = {},\n): true | PathReason => {\n const { actor, authorize } = options;\n const next = applyMerge(transition.to.merge, record, changes);\n\n const from: SideReason = {};\n const fromPredicate = checkRule(transition.from.predicate, record as Row);\n if (fromPredicate !== true) from.predicate = predicateReason(fromPredicate);\n if (denies(authorize, transition.from.permission, record as Row, actor))\n from.permission = 'not authorized';\n\n const to: SideReason = {};\n const toPredicate = checkRule(transition.to.predicate, next as Row);\n if (toPredicate !== true) to.predicate = predicateReason(toPredicate);\n if (denies(authorize, transition.to.permission, next as Row, actor))\n to.permission = 'not authorized';\n\n const reason: PathReason = {};\n if (from.predicate || from.permission) reason.from = from;\n if (to.predicate || to.permission) reason.to = to;\n return reason.from || reason.to ? reason : true;\n};\n","import type { PathReason, Reason } from './types';\n\nconst describePath = (path: PathReason): string => {\n const segs: string[] = [];\n if (path.from?.predicate) segs.push(`from: ${path.from.predicate}`);\n if (path.from?.permission) segs.push(`from: ${path.from.permission}`);\n if (path.to?.predicate) segs.push(`to: ${path.to.predicate}`);\n if (path.to?.permission) segs.push(`to: ${path.to.permission}`);\n return segs.join('; ') || 'unknown';\n};\n\n/** Build a human-readable message from a structured {@link Reason} (logs / UI / error bodies). */\nexport const describe = (reason: Reason): string => {\n if (reason.paths.length === 0) return 'no transition path available';\n if (reason.paths.length === 1) return describePath(reason.paths[0]);\n return reason.paths.map((path, i) => `path ${i}: ${describePath(path)}`).join(' | ');\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport type { ActionRule, Actor, Authorize, Row } from '../types';\nimport type { RebacOptions, RebacSchema } from './types';\n\ntype Context = {\n schema: RebacSchema;\n resolveModel?: (model: string, relationSegment: string) => string;\n isSuperadmin?: (actor: Actor) => boolean;\n};\n\nconst evaluate = (\n ctx: Context,\n model: string,\n record: Row,\n actor: Actor,\n rule: ActionRule,\n visited: Set<string>,\n): boolean => {\n if (ctx.isSuperadmin?.(actor)) return true;\n if (rule === null) return false;\n\n // string → delegate to the named action on this model, additively merged with any per-row override.\n if (typeof rule === 'string') {\n const schemaRule = ctx.schema[model]?.actions[rule] ?? null;\n const rowRules = record.permissionRules as Record<string, ActionRule> | null | undefined;\n const rowRule = rowRules?.[rule];\n const merged: ActionRule = rowRule !== undefined ? { any: [schemaRule, rowRule] } : schemaRule;\n return evaluate(ctx, model, record, actor, merged, visited);\n }\n\n // { rel, action } → walk the relation (dot-paths supported), then check `action` on the target.\n if ('rel' in rule && 'action' in rule) {\n const segments = rule.rel.split('.');\n let current: Row = record;\n let currentModel = model;\n for (const segment of segments) {\n const related = current[segment] as Row | null | undefined;\n if (!related) return false;\n currentModel = ctx.resolveModel ? ctx.resolveModel(currentModel, segment) : segment;\n current = related;\n }\n const key = `${currentModel}:${String(current.id)}:${rule.action}`;\n if (visited.has(key)) throw new Error(`Cycle detected in permission graph: ${key}`);\n visited.add(key);\n return evaluate(ctx, currentModel, current, actor, rule.action, visited);\n }\n\n // { self } → record[field] matches the current actor.\n if ('self' in rule) {\n const actorId = actor?.id ?? null;\n return actorId !== null && record[rule.self] === actorId;\n }\n\n // { rule } → ABAC predicate (json-rules) over the record.\n if ('rule' in rule) return checkRule(rule.rule, record) === true;\n\n // Fork `visited` per branch — parallel paths through any/all aren't cycles.\n if ('any' in rule)\n return rule.any.some((sub) => evaluate(ctx, model, record, actor, sub, new Set(visited)));\n if ('all' in rule)\n return rule.all.every((sub) => evaluate(ctx, model, record, actor, sub, new Set(visited)));\n\n return false;\n};\n\n/**\n * A reference rebac evaluator — one implementation of the injected {@link Authorize} seam,\n * bound to a single `model`. Faithful to `@template/permissions`' `rebac/check` (string-delegate,\n * relation walk with cycle detection, self, json-rules `{ rule }`, any/all, per-row\n * `permissionRules` override) but standalone. Swap it for a richer authorizer in production;\n * this is slated to graduate into `@inixiative/permissions`.\n */\nexport const makeRebacAuthorize = (options: RebacOptions & { model: string }): Authorize => {\n const { model, ...rest } = options;\n return (rule, record, actor) => evaluate(rest, model, record, actor, rule, new Set());\n};\n\n/** Curried form: `createRebac({ schema })(model)` → an {@link Authorize} for that model. */\nexport const createRebac =\n (options: RebacOptions) =>\n (model: string): Authorize =>\n makeRebacAuthorize({ ...options, model });\n","import { check as checkRule, toPrisma } from '@inixiative/json-rules';\nimport { checkPath } from './check';\nimport type {\n Action,\n ActionRule,\n AuthorizeOptions,\n CheckResult,\n PathReason,\n Row,\n TransitionMap,\n} from './types';\n\nconst getAction = (rules: TransitionMap, resource: string, action: string): Action => {\n const found = rules[resource]?.[action];\n if (!found)\n throw new Error(`transition: no action \"${action}\" registered on resource \"${resource}\"`);\n return found;\n};\n\n/**\n * Authoritative check: the FIRST path whose `from` matches the current record, whose `to` matches\n * the merged record, and whose permissions all pass, wins → `true`. If none pass, returns a\n * {@link Reason} with one {@link PathReason} per candidate path tried.\n *\n * `resource` is the (map-qualified) key into the map — e.g. `db:Inquiry`. Cross-source `permission`\n * checks are handled by the injected {@link Authorize} (wire it to a bridge-aware rebac check, bound\n * to this resource); a `predicate` that reads a bridged relation expects a stitched record.\n */\nexport const checkTransition = (\n rules: TransitionMap,\n resource: string,\n action: string,\n record: Row,\n changes: Row = {},\n options: AuthorizeOptions = {},\n): CheckResult => {\n const found = getAction(rules, resource, action);\n const paths: PathReason[] = [];\n for (const path of found.paths) {\n const result = checkPath(path, record, changes, options);\n if (result === true) return true;\n paths.push(result);\n }\n return { paths };\n};\n\n/**\n * Affordance hint: which actions are offerable from `record` right now. Evaluates ONLY the `from`\n * side (predicate + `from` permission against the current record) — `to` needs the merged record,\n * which doesn't exist without proposed changes, so it defers to {@link checkTransition}.\n */\nexport const available = (\n rules: TransitionMap,\n resource: string,\n record: Row,\n options: AuthorizeOptions = {},\n): string[] => {\n const actions = rules[resource];\n if (!actions) return [];\n const { actor, authorize } = options;\n\n const allows = (rule: ActionRule | undefined, rec: Row): boolean =>\n !authorize || rule === undefined || authorize(rule, rec, actor);\n\n return Object.entries(actions)\n .filter(([, action]) =>\n action.paths.some(\n (path) =>\n checkRule(path.from.predicate, record) === true && allows(path.from.permission, record),\n ),\n )\n .map(([action]) => action);\n};\n\n/**\n * Set query: one OR'd Prisma `where` matching every record currently eligible for `action`\n * (the union of all its paths' `from` predicates). Empty action → match-nothing.\n */\nexport const eligible = (rules: TransitionMap, resource: string, action: string): Row => {\n const found = getAction(rules, resource, action);\n const { steps } = toPrisma({ any: found.paths.map((path) => path.from.predicate) });\n // json-rules guarantees the last step is the WhereStep. Assert it loudly rather than cast-and-swallow:\n // a silent `{}` fallback would mean match-EVERYTHING — the dangerous inverse of match-nothing.\n const last = steps[steps.length - 1] as { operation?: string; where?: Row } | undefined;\n if (last?.operation !== 'where' || last.where === undefined)\n throw new Error('transition: expected a terminal WhereStep from toPrisma; got none');\n return last.where;\n};\n","import { isSerializableMerge } from './merge';\nimport type { Transition } from './types';\n\n/**\n * Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?\n *\n * Predicates (json-rules) and permissions (ActionRule) are always plain JSON; the only\n * non-data escape hatch is a `to.merge` callback. So serializability reduces to the merge.\n */\nexport const isSerializable = (transition: Transition): boolean =>\n isSerializableMerge(transition.to.merge);\n","import {\n type Condition,\n checkRuleAgainstLens,\n type Lens,\n type LensNarrowing,\n validateRule,\n} from '@inixiative/json-rules';\nimport { isSerializableMerge } from './merge';\nimport type { ActionRule, Merge, Side, ToSide, Transition } from './types';\n\nexport type ValidationIssue = { path: string; message: string };\nexport type ValidationResult = { ok: boolean; errors: ValidationIssue[] };\n\nexport type ValidateOptions = {\n /** Optional field/relation allowlist; passed through to json-rules lens validation per predicate. */\n lens?: Lens | LensNarrowing;\n /** Reject callback merges (use when the transition must be persistable / tenant-configured). */\n requireSerializable?: boolean;\n};\n\nconst MERGE_KEYWORDS = new Set(['spread', 'deepMerge']);\nconst ARRAY_KINDS = new Set(['append', 'appendUnique']);\n\nconst validatePredicate = (\n predicate: Condition,\n errors: ValidationIssue[],\n path: string,\n lens?: Lens | LensNarrowing,\n): void => {\n const result = validateRule(predicate);\n for (const issue of result.errors)\n errors.push({ path: `${path}.${issue.path}`, message: issue.message });\n if (lens) {\n const lensCheck = checkRuleAgainstLens(predicate, lens);\n for (const violation of lensCheck.violations)\n errors.push({ path: `${path}.${violation.path}`, message: violation.reason });\n }\n};\n\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined || rule === null || typeof rule === 'string') return;\n if ('rule' in rule) {\n const result = validateRule(rule.rule);\n for (const issue of result.errors)\n errors.push({ path: `${path}.rule.${issue.path}`, message: issue.message });\n return;\n }\n if ('rel' in rule) {\n if (!rule.rel || !rule.action)\n errors.push({ path, message: 'rel-rule requires non-empty `rel` and `action`' });\n return;\n }\n if ('self' in rule) {\n if (!rule.self) errors.push({ path, message: 'self-rule requires a non-empty field name' });\n return;\n }\n if ('any' in rule) {\n rule.any.forEach((sub, i) => {\n validatePermission(sub, errors, `${path}.any[${i}]`);\n });\n return;\n }\n if ('all' in rule) {\n rule.all.forEach((sub, i) => {\n validatePermission(sub, errors, `${path}.all[${i}]`);\n });\n return;\n }\n errors.push({ path, message: 'unrecognized ActionRule shape' });\n};\n\nconst validateMerge = (merge: Merge | undefined, errors: ValidationIssue[], path: string): void => {\n if (merge === undefined || typeof merge === 'function') return;\n if (typeof merge === 'string') {\n if (!MERGE_KEYWORDS.has(merge))\n errors.push({ path, message: `unknown merge strategy \"${merge}\"` });\n return;\n }\n if (!ARRAY_KINDS.has(merge.kind))\n errors.push({ path, message: `unknown merge kind \"${merge.kind}\"` });\n else if (!merge.path) errors.push({ path, message: `merge \"${merge.kind}\" requires a \\`path\\`` });\n};\n\nconst validateSide = (\n side: Side | ToSide,\n errors: ValidationIssue[],\n path: string,\n options: ValidateOptions,\n): void => {\n validatePredicate(side.predicate, errors, `${path}.predicate`, options.lens);\n validatePermission(side.permission, errors, `${path}.permission`);\n if (side.requires !== undefined && (typeof side.requires !== 'object' || side.requires === null))\n errors.push({\n path: `${path}.requires`,\n message: '`requires` must be a Prisma-include-shaped object',\n });\n if ('merge' in side) validateMerge(side.merge, errors, `${path}.merge`);\n};\n\n/**\n * Authoring validation for a single transition — run on save before persisting a tenant config.\n * Predicate validity delegates to json-rules (`validateRule`, plus `checkRuleAgainstLens` when a\n * `lens` is supplied for field/relation scoping); merge strategy and permission shape are checked here.\n */\nexport const validateTransition = (\n transition: Transition,\n options: ValidateOptions = {},\n): ValidationResult => {\n const errors: ValidationIssue[] = [];\n validateSide(transition.from, errors, 'from', options);\n validateSide(transition.to, errors, 'to', options);\n if (options.requireSerializable && !isSerializableMerge(transition.to.merge))\n errors.push({\n path: 'to.merge',\n message: 'callback merge is not serializable; use a keyword strategy',\n });\n return { ok: errors.length === 0, errors };\n};\n"]}
package/dist/index.d.cts CHANGED
@@ -2,16 +2,10 @@ import { Condition, Lens, LensNarrowing } from '@inixiative/json-rules';
2
2
 
3
3
  type Row = Record<string, unknown>;
4
4
  /**
5
- * The serializable permission algebra.
6
- *
7
- * Re-declared here — deliberately NOT imported from any app's permissions package — so
8
- * `@inixiative/transitions` stays a zero-app-dependency primitive. It is structurally
9
- * identical to the rebac `ActionRule` used by `@template/permissions`, so a permission
10
- * rule authored over there deserializes into a transition's `permission` field unchanged.
11
- *
12
- * The kernel never *interprets* an ActionRule; it hands the rule to an injected
13
- * {@link Authorize} callback. Resolving `string` (delegate) and `{ rel, action }`
14
- * (relation walk) requires a model + schema, which lives in the authorizer, not here.
5
+ * The serializable permission algebra. Re-declared here (not imported from any app's
6
+ * permissions package) so this stays a zero-app-dependency primitive; structurally identical
7
+ * to `@template/permissions`' rebac `ActionRule`. The kernel never interprets it — it hands the
8
+ * rule to an injected {@link Authorize} callback.
15
9
  */
16
10
  type ActionRule = string | {
17
11
  rel: string;
@@ -29,10 +23,8 @@ type Actor = ({
29
23
  id?: string | null;
30
24
  } & Row) | null | undefined;
31
25
  /**
32
- * Injected permission evaluator. Model-free by design: the kernel knows nothing about
33
- * models or schemas, so the consumer closes over whatever its rebac needs (see
34
- * {@link makeRebacAuthorize} for the reference implementation). Returns a bare boolean —
35
- * authz is yes/no; the structured-reason machinery lives in the kernel.
26
+ * Injected permission evaluator. Model-free: the kernel knows nothing about models or schemas,
27
+ * so the consumer closes over whatever its rebac needs (see {@link makeRebacAuthorize}).
36
28
  */
37
29
  type Authorize = (rule: ActionRule, record: Row, actor: Actor) => boolean;
38
30
  /** Serializable merge keywords (Mongo-flavored). Array strategies are field-scoped. */
@@ -48,9 +40,9 @@ type Merge<R extends Row = Row> = ((record: R, changes: Partial<R>) => R) | Merg
48
40
  /** Prisma-include-shaped metadata: the relations a side's predicate reads. Kernel ignores it. */
49
41
  type Include = Record<string, unknown>;
50
42
  /**
51
- * One half of a transition. `predicate` (legality) and `permission` (authz) are evaluated
52
- * against the SAME record — and which record is the load-bearing asymmetry:
53
- * `from.*` reads the CURRENT record, `to.*` reads the RESULTING (merged) record.
43
+ * One half of a transition. `predicate` (legality) and `permission` (authz) are both evaluated
44
+ * against the SAME record — the load-bearing asymmetry is WHICH record: `from.*` reads the
45
+ * CURRENT record, `to.*` reads the RESULTING (merged) record.
54
46
  */
55
47
  type Side = {
56
48
  predicate: Condition;
@@ -66,59 +58,47 @@ type Transition<R extends Row = Row> = {
66
58
  to: ToSide<R>;
67
59
  };
68
60
  /**
69
- * A named verb: the OR of its edges. An object (not a bare `Transition[]`) because the
70
- * action is the unit of authorization (`permission`, ANDed with each side) and affordance
71
- * (`label`).
61
+ * A named verb: the OR of its edges. An object (not a bare `Transition[]`) so the action can
62
+ * carry affordance metadata (`label`). Authorization lives on the per-side `permission`s, which
63
+ * always read a concrete record — there is no record-free action-level permission.
72
64
  */
73
65
  type Action<R extends Row = Row> = {
74
66
  paths: Transition<R>[];
75
- permission?: ActionRule;
76
67
  label?: string;
77
68
  };
78
- /** `model → verb → Action`. Mirrors the shape of a rebac schema. */
69
+ /** `resource → action → Action`, where `resource` is the (map-qualified) key — e.g. `db:Inquiry`,
70
+ * matching `@inixiative/permissions`' rebac schema keys so a transition's `permission` resolves
71
+ * against the same resource identity. */
79
72
  type TransitionMap = Record<string, Record<string, Action>>;
80
- type FailureKind = 'no-from' | 'no-to' | 'unauthorized';
81
- type AuthzLevel = 'action' | 'from' | 'to';
82
- type PathFailure = {
83
- from?: string;
84
- to?: string;
85
- authz?: AuthzLevel;
73
+ /** Why one side failed. Both keys are independent; either, both, or neither may be set. */
74
+ type SideReason = {
75
+ predicate?: string;
76
+ permission?: string;
86
77
  };
87
- type Reason = PathFailure & {
88
- kind: FailureKind;
89
- paths?: PathFailure[];
78
+ /** Why one candidate path failed — `from` and `to` reported separately. */
79
+ type PathReason = {
80
+ from?: SideReason;
81
+ to?: SideReason;
90
82
  };
91
- type CheckResult<R extends Row = Row> = {
92
- ok: true;
93
- path: Transition<R>;
94
- } | {
95
- ok: false;
96
- reason: Reason;
83
+ /** Why an action failed: one {@link PathReason} per candidate path that was tried. */
84
+ type Reason = {
85
+ paths: PathReason[];
97
86
  };
87
+ /** `true` when the transition is allowed, else a structured {@link Reason}. */
88
+ type CheckResult = true | Reason;
98
89
  /** Options threaded into a check. Omit `authorize` to evaluate legality only. */
99
- type CheckOptions = {
100
- actor?: Actor;
101
- authorize?: Authorize;
102
- /** Action-level baseline permission, ANDed against the current record (supplied by the registry). */
103
- basePermission?: ActionRule;
104
- };
105
- /** Options for affordance/check at the registry level. */
106
90
  type AuthorizeOptions = {
107
91
  actor?: Actor;
108
92
  authorize?: Authorize;
109
93
  };
110
94
 
111
95
  /**
112
- * The kernel: evaluate one atomic transition.
113
- *
114
- * Legality (json-rules) AND authz (injected, per side), with the load-bearing asymmetry —
115
- * `from.*` reads the current `record`, `to.*` reads the merged `next` record. Authz order is
116
- * action baseline → from → to, all ANDed. Returns a structured {@link CheckResult} whose
117
- * `reason.kind` lets a caller map illegal → 409 vs unauthorized → 403.
118
- *
119
- * Omit `options.authorize` to check legality only.
96
+ * The kernel: evaluate one atomic edge. Reports every failure rather than short-circuiting —
97
+ * `from`/`to` and predicate/permission are independent slots — so a caller sees the whole
98
+ * picture. `from.*` reads the current `record`, `to.*` reads the merged `next` record. Returns
99
+ * `true` when the edge is allowed, else the {@link PathReason}. Omit `authorize` for legality only.
120
100
  */
121
- declare const checkTransition: <R extends Row>(transition: Transition<R>, record: R, changes?: Partial<R>, options?: CheckOptions) => CheckResult<R>;
101
+ declare const checkPath: <R extends Row>(transition: Transition<R>, record: R, changes?: Partial<R>, options?: AuthorizeOptions) => true | PathReason;
122
102
 
123
103
  /** Build a human-readable message from a structured {@link Reason} (logs / UI / error bodies). */
124
104
  declare const describe: (reason: Reason) => string;
@@ -167,22 +147,26 @@ declare const makeRebacAuthorize: (options: RebacOptions & {
167
147
  declare const createRebac: (options: RebacOptions) => (model: string) => Authorize;
168
148
 
169
149
  /**
170
- * Authoritative check: the FIRST path whose `from` matches the current record, whose `to`
171
- * matches the merged record, and whose permissions all pass, wins. If none pass, returns the
172
- * aggregated structured failure (see {@link aggregate}).
150
+ * Authoritative check: the FIRST path whose `from` matches the current record, whose `to` matches
151
+ * the merged record, and whose permissions all pass, wins → `true`. If none pass, returns a
152
+ * {@link Reason} with one {@link PathReason} per candidate path tried.
153
+ *
154
+ * `resource` is the (map-qualified) key into the map — e.g. `db:Inquiry`. Cross-source `permission`
155
+ * checks are handled by the injected {@link Authorize} (wire it to a bridge-aware rebac check, bound
156
+ * to this resource); a `predicate` that reads a bridged relation expects a stitched record.
173
157
  */
174
- declare const check: (map: TransitionMap, model: string, verb: string, record: Row, changes?: Row, options?: AuthorizeOptions) => CheckResult;
158
+ declare const checkTransition: (rules: TransitionMap, resource: string, action: string, record: Row, changes?: Row, options?: AuthorizeOptions) => CheckResult;
175
159
  /**
176
- * Affordance hint: which verbs are offerable from `record` right now. Evaluates ONLY the
177
- * `from` side (predicate + `action`/`from` permission against the current record) — `to` needs
178
- * the merged record, which doesn't exist without proposed changes, so it defers to {@link check}.
160
+ * Affordance hint: which actions are offerable from `record` right now. Evaluates ONLY the `from`
161
+ * side (predicate + `from` permission against the current record) — `to` needs the merged record,
162
+ * which doesn't exist without proposed changes, so it defers to {@link checkTransition}.
179
163
  */
180
- declare const available: (map: TransitionMap, model: string, record: Row, options?: AuthorizeOptions) => string[];
164
+ declare const available: (rules: TransitionMap, resource: string, record: Row, options?: AuthorizeOptions) => string[];
181
165
  /**
182
- * Set query: one OR'd Prisma `where` matching every record currently eligible for `verb`
166
+ * Set query: one OR'd Prisma `where` matching every record currently eligible for `action`
183
167
  * (the union of all its paths' `from` predicates). Empty action → match-nothing.
184
168
  */
185
- declare const eligible: (map: TransitionMap, model: string, verb: string) => Row;
169
+ declare const eligible: (rules: TransitionMap, resource: string, action: string) => Row;
186
170
 
187
171
  /**
188
172
  * Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?
@@ -213,4 +197,4 @@ type ValidateOptions = {
213
197
  */
214
198
  declare const validateTransition: (transition: Transition, options?: ValidateOptions) => ValidationResult;
215
199
 
216
- export { type Action, type ActionRule, type Actor, type Authorize, type AuthorizeOptions, type AuthzLevel, type CheckOptions, type CheckResult, type FailureKind, type Include, type Merge, type MergeStrategy, type ModelPermission, type PathFailure, type Reason, type RebacOptions, type RebacSchema, type Row, type Side, type ToSide, type Transition, type TransitionMap, type ValidateOptions, type ValidationIssue, type ValidationResult, applyMerge, available, check, checkTransition, createRebac, describe, eligible, isSerializable, isSerializableMerge, makeRebacAuthorize, validateTransition };
200
+ export { type Action, type ActionRule, type Actor, type Authorize, type AuthorizeOptions, type CheckResult, type Include, type Merge, type MergeStrategy, type ModelPermission, type PathReason, type Reason, type RebacOptions, type RebacSchema, type Row, type Side, type SideReason, type ToSide, type Transition, type TransitionMap, type ValidateOptions, type ValidationIssue, type ValidationResult, applyMerge, available, checkPath, checkTransition, createRebac, describe, eligible, isSerializable, isSerializableMerge, makeRebacAuthorize, validateTransition };
package/dist/index.d.ts CHANGED
@@ -2,16 +2,10 @@ import { Condition, Lens, LensNarrowing } from '@inixiative/json-rules';
2
2
 
3
3
  type Row = Record<string, unknown>;
4
4
  /**
5
- * The serializable permission algebra.
6
- *
7
- * Re-declared here — deliberately NOT imported from any app's permissions package — so
8
- * `@inixiative/transitions` stays a zero-app-dependency primitive. It is structurally
9
- * identical to the rebac `ActionRule` used by `@template/permissions`, so a permission
10
- * rule authored over there deserializes into a transition's `permission` field unchanged.
11
- *
12
- * The kernel never *interprets* an ActionRule; it hands the rule to an injected
13
- * {@link Authorize} callback. Resolving `string` (delegate) and `{ rel, action }`
14
- * (relation walk) requires a model + schema, which lives in the authorizer, not here.
5
+ * The serializable permission algebra. Re-declared here (not imported from any app's
6
+ * permissions package) so this stays a zero-app-dependency primitive; structurally identical
7
+ * to `@template/permissions`' rebac `ActionRule`. The kernel never interprets it — it hands the
8
+ * rule to an injected {@link Authorize} callback.
15
9
  */
16
10
  type ActionRule = string | {
17
11
  rel: string;
@@ -29,10 +23,8 @@ type Actor = ({
29
23
  id?: string | null;
30
24
  } & Row) | null | undefined;
31
25
  /**
32
- * Injected permission evaluator. Model-free by design: the kernel knows nothing about
33
- * models or schemas, so the consumer closes over whatever its rebac needs (see
34
- * {@link makeRebacAuthorize} for the reference implementation). Returns a bare boolean —
35
- * authz is yes/no; the structured-reason machinery lives in the kernel.
26
+ * Injected permission evaluator. Model-free: the kernel knows nothing about models or schemas,
27
+ * so the consumer closes over whatever its rebac needs (see {@link makeRebacAuthorize}).
36
28
  */
37
29
  type Authorize = (rule: ActionRule, record: Row, actor: Actor) => boolean;
38
30
  /** Serializable merge keywords (Mongo-flavored). Array strategies are field-scoped. */
@@ -48,9 +40,9 @@ type Merge<R extends Row = Row> = ((record: R, changes: Partial<R>) => R) | Merg
48
40
  /** Prisma-include-shaped metadata: the relations a side's predicate reads. Kernel ignores it. */
49
41
  type Include = Record<string, unknown>;
50
42
  /**
51
- * One half of a transition. `predicate` (legality) and `permission` (authz) are evaluated
52
- * against the SAME record — and which record is the load-bearing asymmetry:
53
- * `from.*` reads the CURRENT record, `to.*` reads the RESULTING (merged) record.
43
+ * One half of a transition. `predicate` (legality) and `permission` (authz) are both evaluated
44
+ * against the SAME record — the load-bearing asymmetry is WHICH record: `from.*` reads the
45
+ * CURRENT record, `to.*` reads the RESULTING (merged) record.
54
46
  */
55
47
  type Side = {
56
48
  predicate: Condition;
@@ -66,59 +58,47 @@ type Transition<R extends Row = Row> = {
66
58
  to: ToSide<R>;
67
59
  };
68
60
  /**
69
- * A named verb: the OR of its edges. An object (not a bare `Transition[]`) because the
70
- * action is the unit of authorization (`permission`, ANDed with each side) and affordance
71
- * (`label`).
61
+ * A named verb: the OR of its edges. An object (not a bare `Transition[]`) so the action can
62
+ * carry affordance metadata (`label`). Authorization lives on the per-side `permission`s, which
63
+ * always read a concrete record — there is no record-free action-level permission.
72
64
  */
73
65
  type Action<R extends Row = Row> = {
74
66
  paths: Transition<R>[];
75
- permission?: ActionRule;
76
67
  label?: string;
77
68
  };
78
- /** `model → verb → Action`. Mirrors the shape of a rebac schema. */
69
+ /** `resource → action → Action`, where `resource` is the (map-qualified) key — e.g. `db:Inquiry`,
70
+ * matching `@inixiative/permissions`' rebac schema keys so a transition's `permission` resolves
71
+ * against the same resource identity. */
79
72
  type TransitionMap = Record<string, Record<string, Action>>;
80
- type FailureKind = 'no-from' | 'no-to' | 'unauthorized';
81
- type AuthzLevel = 'action' | 'from' | 'to';
82
- type PathFailure = {
83
- from?: string;
84
- to?: string;
85
- authz?: AuthzLevel;
73
+ /** Why one side failed. Both keys are independent; either, both, or neither may be set. */
74
+ type SideReason = {
75
+ predicate?: string;
76
+ permission?: string;
86
77
  };
87
- type Reason = PathFailure & {
88
- kind: FailureKind;
89
- paths?: PathFailure[];
78
+ /** Why one candidate path failed — `from` and `to` reported separately. */
79
+ type PathReason = {
80
+ from?: SideReason;
81
+ to?: SideReason;
90
82
  };
91
- type CheckResult<R extends Row = Row> = {
92
- ok: true;
93
- path: Transition<R>;
94
- } | {
95
- ok: false;
96
- reason: Reason;
83
+ /** Why an action failed: one {@link PathReason} per candidate path that was tried. */
84
+ type Reason = {
85
+ paths: PathReason[];
97
86
  };
87
+ /** `true` when the transition is allowed, else a structured {@link Reason}. */
88
+ type CheckResult = true | Reason;
98
89
  /** Options threaded into a check. Omit `authorize` to evaluate legality only. */
99
- type CheckOptions = {
100
- actor?: Actor;
101
- authorize?: Authorize;
102
- /** Action-level baseline permission, ANDed against the current record (supplied by the registry). */
103
- basePermission?: ActionRule;
104
- };
105
- /** Options for affordance/check at the registry level. */
106
90
  type AuthorizeOptions = {
107
91
  actor?: Actor;
108
92
  authorize?: Authorize;
109
93
  };
110
94
 
111
95
  /**
112
- * The kernel: evaluate one atomic transition.
113
- *
114
- * Legality (json-rules) AND authz (injected, per side), with the load-bearing asymmetry —
115
- * `from.*` reads the current `record`, `to.*` reads the merged `next` record. Authz order is
116
- * action baseline → from → to, all ANDed. Returns a structured {@link CheckResult} whose
117
- * `reason.kind` lets a caller map illegal → 409 vs unauthorized → 403.
118
- *
119
- * Omit `options.authorize` to check legality only.
96
+ * The kernel: evaluate one atomic edge. Reports every failure rather than short-circuiting —
97
+ * `from`/`to` and predicate/permission are independent slots — so a caller sees the whole
98
+ * picture. `from.*` reads the current `record`, `to.*` reads the merged `next` record. Returns
99
+ * `true` when the edge is allowed, else the {@link PathReason}. Omit `authorize` for legality only.
120
100
  */
121
- declare const checkTransition: <R extends Row>(transition: Transition<R>, record: R, changes?: Partial<R>, options?: CheckOptions) => CheckResult<R>;
101
+ declare const checkPath: <R extends Row>(transition: Transition<R>, record: R, changes?: Partial<R>, options?: AuthorizeOptions) => true | PathReason;
122
102
 
123
103
  /** Build a human-readable message from a structured {@link Reason} (logs / UI / error bodies). */
124
104
  declare const describe: (reason: Reason) => string;
@@ -167,22 +147,26 @@ declare const makeRebacAuthorize: (options: RebacOptions & {
167
147
  declare const createRebac: (options: RebacOptions) => (model: string) => Authorize;
168
148
 
169
149
  /**
170
- * Authoritative check: the FIRST path whose `from` matches the current record, whose `to`
171
- * matches the merged record, and whose permissions all pass, wins. If none pass, returns the
172
- * aggregated structured failure (see {@link aggregate}).
150
+ * Authoritative check: the FIRST path whose `from` matches the current record, whose `to` matches
151
+ * the merged record, and whose permissions all pass, wins → `true`. If none pass, returns a
152
+ * {@link Reason} with one {@link PathReason} per candidate path tried.
153
+ *
154
+ * `resource` is the (map-qualified) key into the map — e.g. `db:Inquiry`. Cross-source `permission`
155
+ * checks are handled by the injected {@link Authorize} (wire it to a bridge-aware rebac check, bound
156
+ * to this resource); a `predicate` that reads a bridged relation expects a stitched record.
173
157
  */
174
- declare const check: (map: TransitionMap, model: string, verb: string, record: Row, changes?: Row, options?: AuthorizeOptions) => CheckResult;
158
+ declare const checkTransition: (rules: TransitionMap, resource: string, action: string, record: Row, changes?: Row, options?: AuthorizeOptions) => CheckResult;
175
159
  /**
176
- * Affordance hint: which verbs are offerable from `record` right now. Evaluates ONLY the
177
- * `from` side (predicate + `action`/`from` permission against the current record) — `to` needs
178
- * the merged record, which doesn't exist without proposed changes, so it defers to {@link check}.
160
+ * Affordance hint: which actions are offerable from `record` right now. Evaluates ONLY the `from`
161
+ * side (predicate + `from` permission against the current record) — `to` needs the merged record,
162
+ * which doesn't exist without proposed changes, so it defers to {@link checkTransition}.
179
163
  */
180
- declare const available: (map: TransitionMap, model: string, record: Row, options?: AuthorizeOptions) => string[];
164
+ declare const available: (rules: TransitionMap, resource: string, record: Row, options?: AuthorizeOptions) => string[];
181
165
  /**
182
- * Set query: one OR'd Prisma `where` matching every record currently eligible for `verb`
166
+ * Set query: one OR'd Prisma `where` matching every record currently eligible for `action`
183
167
  * (the union of all its paths' `from` predicates). Empty action → match-nothing.
184
168
  */
185
- declare const eligible: (map: TransitionMap, model: string, verb: string) => Row;
169
+ declare const eligible: (rules: TransitionMap, resource: string, action: string) => Row;
186
170
 
187
171
  /**
188
172
  * Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?
@@ -213,4 +197,4 @@ type ValidateOptions = {
213
197
  */
214
198
  declare const validateTransition: (transition: Transition, options?: ValidateOptions) => ValidationResult;
215
199
 
216
- export { type Action, type ActionRule, type Actor, type Authorize, type AuthorizeOptions, type AuthzLevel, type CheckOptions, type CheckResult, type FailureKind, type Include, type Merge, type MergeStrategy, type ModelPermission, type PathFailure, type Reason, type RebacOptions, type RebacSchema, type Row, type Side, type ToSide, type Transition, type TransitionMap, type ValidateOptions, type ValidationIssue, type ValidationResult, applyMerge, available, check, checkTransition, createRebac, describe, eligible, isSerializable, isSerializableMerge, makeRebacAuthorize, validateTransition };
200
+ export { type Action, type ActionRule, type Actor, type Authorize, type AuthorizeOptions, type CheckResult, type Include, type Merge, type MergeStrategy, type ModelPermission, type PathReason, type Reason, type RebacOptions, type RebacSchema, type Row, type Side, type SideReason, type ToSide, type Transition, type TransitionMap, type ValidateOptions, type ValidationIssue, type ValidationResult, applyMerge, available, checkPath, checkTransition, createRebac, describe, eligible, isSerializable, isSerializableMerge, makeRebacAuthorize, validateTransition };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import {check,toPrisma,validateRule,checkRuleAgainstLens}from'@inixiative/json-rules';import {mergeWith,cloneDeep,get,set,uniqWith,isEqual}from'lodash-es';var y=e=>Array.isArray(e)?e:e===void 0?[]:[e],O=(e,t)=>Array.isArray(t)?t:void 0,l=e=>typeof e!="function",k=(e,t,n={})=>{if(typeof e=="function")return e(t,n);let i=e??"spread";if(i==="spread")return {...t,...n};if(i==="deepMerge")return mergeWith(cloneDeep(t),cloneDeep(n),O);let{kind:o,path:s}=i,r=cloneDeep({...t,...n}),p=[...y(get(t,s)),...y(get(n,s))];return set(r,s,o==="appendUnique"?uniqWith(p,isEqual):p),r};var A=e=>typeof e=="string"?e:"predicate not satisfied",d=(e,t,n,i)=>!e||t===void 0?false:!e(t,n,i),b=(e,t,n={},i={})=>{let{actor:o,authorize:s,basePermission:r}=i,p=k(e.to.merge,t,n),a=check(e.from.predicate,t);if(a!==true)return {ok:false,reason:{kind:"no-from",from:A(a)}};let u=check(e.to.predicate,p);return u!==true?{ok:false,reason:{kind:"no-to",to:A(u)}}:d(s,r,t,o)?{ok:false,reason:{kind:"unauthorized",authz:"action"}}:d(s,e.from.permission,t,o)?{ok:false,reason:{kind:"unauthorized",authz:"from"}}:d(s,e.to.permission,p,o)?{ok:false,reason:{kind:"unauthorized",authz:"to"}}:{ok:true,path:e}};var Y=e=>{switch(e.kind){case "no-from":return e.from??"transition is not available from the current state";case "no-to":return e.to??"the resulting state is not a valid target";case "unauthorized":return e.authz?`not authorized (${e.authz}-level permission denied)`:"not authorized";default:return e.kind}};var c=(e,t,n,i,o,s)=>{if(e.isSuperadmin?.(i))return true;if(o===null)return false;if(typeof o=="string"){let r=e.schema[t]?.actions[o]??null,a=n.permissionRules?.[o];return c(e,t,n,i,a!==void 0?{any:[r,a]}:r,s)}if("rel"in o&&"action"in o){let r=o.rel.split("."),p=n,a=t;for(let f of r){let g=p[f];if(!g)return false;a=e.resolveModel?e.resolveModel(a,f):f,p=g;}let u=`${a}:${String(p.id)}:${o.action}`;if(s.has(u))throw new Error(`Cycle detected in permission graph: ${u}`);return s.add(u),c(e,a,p,i,o.action,s)}if("self"in o){let r=i?.id??null;return r!==null&&n[o.self]===r}return "rule"in o?check(o.rule,n)===true:"any"in o?o.any.some(r=>c(e,t,n,i,r,new Set(s))):"all"in o?o.all.every(r=>c(e,t,n,i,r,new Set(s))):false},C=e=>{let{model:t,...n}=e;return (i,o,s)=>c(n,t,o,s,i,new Set)},H=e=>t=>C({...e,model:t});var z=(e,t,n)=>{let i=e[t]?.[n];if(!i)throw new Error(`transition: no action "${n}" registered on model "${t}"`);return i},E=e=>{let t=e.map(({kind:r,paths:p,...a})=>a),n=r=>e.find(p=>p.kind===r),i=n("unauthorized")??n("no-to")??n("no-from");if(!i)return {kind:"no-from",paths:t};let{paths:o,...s}=i;return {...s,paths:t}},te=(e,t,n,i,o={},s={})=>{let r=z(e,t,n),p={...s,basePermission:r.permission},a=[];for(let u of r.paths){let f=b(u,i,o,p);if(f.ok)return f;a.push(f.reason);}return {ok:false,reason:E(a)}},ne=(e,t,n,i={})=>{let o=e[t];if(!o)return [];let{actor:s,authorize:r}=i,p=(a,u)=>!r||a===void 0||r(a,u,s);return Object.entries(o).filter(([,a])=>a.paths.some(u=>check(u.from.predicate,n)===true&&p(a.permission,n)&&p(u.from.permission,n))).map(([a])=>a)},oe=(e,t,n)=>{let i=z(e,t,n),{steps:o}=toPrisma({any:i.paths.map(r=>r.from.predicate)}),s=o[o.length-1];if(s?.operation!=="where"||s.where===void 0)throw new Error("transition: expected a terminal WhereStep from toPrisma; got none");return s.where};var re=e=>l(e.to.merge);var _=new Set(["spread","deepMerge"]),L=new Set(["append","appendUnique"]),N=(e,t,n,i)=>{let o=validateRule(e);for(let s of o.errors)t.push({path:`${n}.${s.path}`,message:s.message});if(i){let s=checkRuleAgainstLens(e,i);for(let r of s.violations)t.push({path:`${n}.${r.path}`,message:r.reason});}},h=(e,t,n)=>{if(!(e==null||typeof e=="string")){if("rule"in e){let i=validateRule(e.rule);for(let o of i.errors)t.push({path:`${n}.rule.${o.path}`,message:o.message});return}if("rel"in e){(!e.rel||!e.action)&&t.push({path:n,message:"rel-rule requires non-empty `rel` and `action`"});return}if("self"in e){e.self||t.push({path:n,message:"self-rule requires a non-empty field name"});return}if("any"in e){e.any.forEach((i,o)=>{h(i,t,`${n}.any[${o}]`);});return}if("all"in e){e.all.forEach((i,o)=>{h(i,t,`${n}.all[${o}]`);});return}t.push({path:n,message:"unrecognized ActionRule shape"});}},W=(e,t,n)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){_.has(e)||t.push({path:n,message:`unknown merge strategy "${e}"`});return}L.has(e.kind)?e.path||t.push({path:n,message:`merge "${e.kind}" requires a \`path\``}):t.push({path:n,message:`unknown merge kind "${e.kind}"`});}},S=(e,t,n,i)=>{N(e.predicate,t,`${n}.predicate`,i.lens),h(e.permission,t,`${n}.permission`),e.requires!==void 0&&(typeof e.requires!="object"||e.requires===null)&&t.push({path:`${n}.requires`,message:"`requires` must be a Prisma-include-shaped object"}),"merge"in e&&W(e.merge,t,`${n}.merge`);},fe=(e,t={})=>{let n=[];return S(e.from,n,"from",t),S(e.to,n,"to",t),t.requireSerializable&&!l(e.to.merge)&&n.push({path:"to.merge",message:"callback merge is not serializable; use a keyword strategy"}),{ok:n.length===0,errors:n}};export{k as applyMerge,ne as available,te as check,b as checkTransition,H as createRebac,Y as describe,oe as eligible,re as isSerializable,l as isSerializableMerge,C as makeRebacAuthorize,fe as validateTransition};//# sourceMappingURL=index.js.map
1
+ import {check,toPrisma,validateRule,checkRuleAgainstLens}from'@inixiative/json-rules';import {mergeWith,cloneDeep,get,set,uniqWith,isEqual}from'lodash-es';var h=e=>Array.isArray(e)?e:e===void 0?[]:[e],O=(e,t)=>Array.isArray(t)?t:void 0,m=e=>typeof e!="function",y=(e,t,n={})=>{if(typeof e=="function")return e(t,n);let i=e??"spread";if(i==="spread")return {...t,...n};if(i==="deepMerge")return mergeWith(cloneDeep(t),cloneDeep(n),O);let{kind:o,path:r}=i,s=cloneDeep({...t,...n}),a=[...h(get(t,r)),...h(get(n,r))];return set(s,r,o==="appendUnique"?uniqWith(a,isEqual):a),s};var A=e=>typeof e=="string"?e:"predicate not satisfied",b=(e,t,n,i)=>!e||t===void 0?false:!e(t,n,i),k=(e,t,n={},i={})=>{let{actor:o,authorize:r}=i,s=y(e.to.merge,t,n),a={},p=check(e.from.predicate,t);p!==true&&(a.predicate=A(p)),b(r,e.from.permission,t,o)&&(a.permission="not authorized");let f={},c=check(e.to.predicate,s);c!==true&&(f.predicate=A(c)),b(r,e.to.permission,s,o)&&(f.permission="not authorized");let u={};return (a.predicate||a.permission)&&(u.from=a),(f.predicate||f.permission)&&(u.to=f),u.from||u.to?u:true};var S=e=>{let t=[];return e.from?.predicate&&t.push(`from: ${e.from.predicate}`),e.from?.permission&&t.push(`from: ${e.from.permission}`),e.to?.predicate&&t.push(`to: ${e.to.predicate}`),e.to?.permission&&t.push(`to: ${e.to.permission}`),t.join("; ")||"unknown"},G=e=>e.paths.length===0?"no transition path available":e.paths.length===1?S(e.paths[0]):e.paths.map((t,n)=>`path ${n}: ${S(t)}`).join(" | ");var l=(e,t,n,i,o,r)=>{if(e.isSuperadmin?.(i))return true;if(o===null)return false;if(typeof o=="string"){let s=e.schema[t]?.actions[o]??null,p=n.permissionRules?.[o];return l(e,t,n,i,p!==void 0?{any:[s,p]}:s,r)}if("rel"in o&&"action"in o){let s=o.rel.split("."),a=n,p=t;for(let c of s){let u=a[c];if(!u)return false;p=e.resolveModel?e.resolveModel(p,c):c,a=u;}let f=`${p}:${String(a.id)}:${o.action}`;if(r.has(f))throw new Error(`Cycle detected in permission graph: ${f}`);return r.add(f),l(e,p,a,i,o.action,r)}if("self"in o){let s=i?.id??null;return s!==null&&n[o.self]===s}return "rule"in o?check(o.rule,n)===true:"any"in o?o.any.some(s=>l(e,t,n,i,s,new Set(r))):"all"in o?o.all.every(s=>l(e,t,n,i,s,new Set(r))):false},v=e=>{let{model:t,...n}=e;return (i,o,r)=>l(n,t,o,r,i,new Set)},H=e=>t=>v({...e,model:t});var $=(e,t,n)=>{let i=e[t]?.[n];if(!i)throw new Error(`transition: no action "${n}" registered on resource "${t}"`);return i},te=(e,t,n,i,o={},r={})=>{let s=$(e,t,n),a=[];for(let p of s.paths){let f=k(p,i,o,r);if(f===true)return true;a.push(f);}return {paths:a}},ne=(e,t,n,i={})=>{let o=e[t];if(!o)return [];let{actor:r,authorize:s}=i,a=(p,f)=>!s||p===void 0||s(p,f,r);return Object.entries(o).filter(([,p])=>p.paths.some(f=>check(f.from.predicate,n)===true&&a(f.from.permission,n))).map(([p])=>p)},oe=(e,t,n)=>{let i=$(e,t,n),{steps:o}=toPrisma({any:i.paths.map(s=>s.from.predicate)}),r=o[o.length-1];if(r?.operation!=="where"||r.where===void 0)throw new Error("transition: expected a terminal WhereStep from toPrisma; got none");return r.where};var se=e=>m(e.to.merge);var L=new Set(["spread","deepMerge"]),j=new Set(["append","appendUnique"]),N=(e,t,n,i)=>{let o=validateRule(e);for(let r of o.errors)t.push({path:`${n}.${r.path}`,message:r.message});if(i){let r=checkRuleAgainstLens(e,i);for(let s of r.violations)t.push({path:`${n}.${s.path}`,message:s.reason});}},g=(e,t,n)=>{if(!(e==null||typeof e=="string")){if("rule"in e){let i=validateRule(e.rule);for(let o of i.errors)t.push({path:`${n}.rule.${o.path}`,message:o.message});return}if("rel"in e){(!e.rel||!e.action)&&t.push({path:n,message:"rel-rule requires non-empty `rel` and `action`"});return}if("self"in e){e.self||t.push({path:n,message:"self-rule requires a non-empty field name"});return}if("any"in e){e.any.forEach((i,o)=>{g(i,t,`${n}.any[${o}]`);});return}if("all"in e){e.all.forEach((i,o)=>{g(i,t,`${n}.all[${o}]`);});return}t.push({path:n,message:"unrecognized ActionRule shape"});}},W=(e,t,n)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){L.has(e)||t.push({path:n,message:`unknown merge strategy "${e}"`});return}j.has(e.kind)?e.path||t.push({path:n,message:`merge "${e.kind}" requires a \`path\``}):t.push({path:n,message:`unknown merge kind "${e.kind}"`});}},M=(e,t,n,i)=>{N(e.predicate,t,`${n}.predicate`,i.lens),g(e.permission,t,`${n}.permission`),e.requires!==void 0&&(typeof e.requires!="object"||e.requires===null)&&t.push({path:`${n}.requires`,message:"`requires` must be a Prisma-include-shaped object"}),"merge"in e&&W(e.merge,t,`${n}.merge`);},ue=(e,t={})=>{let n=[];return M(e.from,n,"from",t),M(e.to,n,"to",t),t.requireSerializable&&!m(e.to.merge)&&n.push({path:"to.merge",message:"callback merge is not serializable; use a keyword strategy"}),{ok:n.length===0,errors:n}};export{y as applyMerge,ne as available,k as checkPath,te as checkTransition,H as createRebac,G as describe,oe as eligible,se as isSerializable,m as isSerializableMerge,v as makeRebacAuthorize,ue as validateTransition};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/merge.ts","../src/check.ts","../src/describe.ts","../src/rebac/authorize.ts","../src/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["toArray","value","replaceArrays","_target","source","isSerializableMerge","merge","applyMerge","record","changes","strategy","mergeWith","cloneDeep","kind","path","base","merged","get","set","uniqWith","isEqual","reasonString","result","denies","authorize","rule","actor","checkTransition","transition","options","basePermission","next","fromResult","checkRule","toResult","describe","reason","evaluate","ctx","model","visited","schemaRule","rowRule","segments","current","currentModel","segment","related","key","actorId","sub","makeRebacAuthorize","rest","createRebac","getAction","map","verb","action","aggregate","failures","paths","_kind","_paths","pick","failure","chosen","_omit","representative","check","opts","available","actions","allows","rec","eligible","steps","toPrisma","last","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","predicate","errors","lens","validateRule","issue","lensCheck","checkRuleAgainstLens","violation","validatePermission","i","validateMerge","validateSide","side","validateTransition"],"mappings":"2JAGA,IAAMA,CAAAA,CAAWC,CAAAA,EACf,MAAM,OAAA,CAAQA,CAAK,CAAA,CAAIA,CAAAA,CAAQA,IAAU,MAAA,CAAY,EAAC,CAAI,CAACA,CAAK,CAAA,CAG5DC,CAAAA,CAAgB,CAACC,CAAAA,CAAkBC,IACvC,KAAA,CAAM,OAAA,CAAQA,CAAM,CAAA,CAAIA,EAAS,MAAA,CAGtBC,CAAAA,CAAuBC,CAAAA,EAA2B,OAAOA,GAAU,UAAA,CAWnEC,CAAAA,CAAa,CACxBD,CAAAA,CACAE,EACAC,CAAAA,CAAsB,EAAC,GACjB,CACN,GAAI,OAAOH,CAAAA,EAAU,UAAA,CAAY,OAAOA,EAAME,CAAAA,CAAQC,CAAO,CAAA,CAE7D,IAA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AE,EAAA,CAAIA,CAAAA,CAAO,SAAW,CAAA,CAAG,MAAA,CAAAA,CAAO,CAC3C","file":"index.js","sourcesContent":["import { cloneDeep, get, isEqual, mergeWith, set, uniqWith } from 'lodash-es';\nimport type { Merge, MergeStrategy, Row } from './types';\n\nconst toArray = (value: unknown): unknown[] =>\n Array.isArray(value) ? value : value === undefined ? [] : [value];\n\n// deepMerge replaces arrays wholesale rather than index-merging them (the intuitive default).\nconst replaceArrays = (_target: unknown, source: unknown): unknown[] | undefined =>\n Array.isArray(source) ? source : undefined;\n\n/** A transition is persistable iff its merge is absent or a keyword strategy (callbacks are not). */\nexport const isSerializableMerge = (merge?: Merge): boolean => typeof merge !== 'function';\n\n/**\n * Produce the resulting record from a current record + proposed changes.\n *\n * - `spread` (default) — shallow overwrite (`{ ...record, ...changes }`)\n * - `deepMerge` — recursive object merge, arrays replaced\n * - `{ kind: 'append', path }` — concat `changes[path]` onto `record[path]`\n * - `{ kind: 'appendUnique', path }` — append + dedupe (deep equality)\n * - a callback — full power, not serializable\n */\nexport const applyMerge = <R extends Row>(\n merge: Merge<R> | undefined,\n record: R,\n changes: Partial<R> = {},\n): R => {\n if (typeof merge === 'function') return merge(record, changes);\n\n const strategy: MergeStrategy = merge ?? 'spread';\n\n if (strategy === 'spread') return { ...record, ...changes };\n // clone BOTH inputs: mergeWith assigns nested objects/arrays from `changes` by reference, which\n // would alias the caller's `changes` into the returned record (a mutation footgun for a pure guard).\n if (strategy === 'deepMerge')\n return mergeWith(cloneDeep(record), cloneDeep(changes), replaceArrays);\n\n // field-scoped array strategies: spread the rest of `changes`, then concat at `path`.\n const { kind, path } = strategy;\n const base = cloneDeep({ ...record, ...changes }) as R;\n const merged = [...toArray(get(record, path)), ...toArray(get(changes, path))];\n set(base as Row, path, kind === 'appendUnique' ? uniqWith(merged, isEqual) : merged);\n return base;\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport { applyMerge } from './merge';\nimport type {\n ActionRule,\n Actor,\n Authorize,\n CheckOptions,\n CheckResult,\n Row,\n Transition,\n} from './types';\n\nconst reasonString = (result: boolean | string): string =>\n typeof result === 'string' ? result : 'predicate not satisfied';\n\n/**\n * Does this permission DENY?\n * - no authorizer injected → can't deny (legality-only mode)\n * - `undefined` rule → permission absent → open → can't deny\n * - any other rule (incl. `null` = terminal deny) → delegate to the authorizer\n */\nconst denies = (\n authorize: Authorize | undefined,\n rule: ActionRule | undefined,\n record: Row,\n actor: Actor,\n): boolean => {\n if (!authorize || rule === undefined) return false;\n return !authorize(rule, record, actor);\n};\n\n/**\n * The kernel: evaluate one atomic transition.\n *\n * Legality (json-rules) AND authz (injected, per side), with the load-bearing asymmetry —\n * `from.*` reads the current `record`, `to.*` reads the merged `next` record. Authz order is\n * action baseline → from → to, all ANDed. Returns a structured {@link CheckResult} whose\n * `reason.kind` lets a caller map illegal → 409 vs unauthorized → 403.\n *\n * Omit `options.authorize` to check legality only.\n */\nexport const checkTransition = <R extends Row>(\n transition: Transition<R>,\n record: R,\n changes: Partial<R> = {},\n options: CheckOptions = {},\n): CheckResult<R> => {\n const { actor, authorize, basePermission } = options;\n const next = applyMerge(transition.to.merge, record, changes);\n\n const fromResult = checkRule(transition.from.predicate, record as Row);\n if (fromResult !== true)\n return { ok: false, reason: { kind: 'no-from', from: reasonString(fromResult) } };\n\n const toResult = checkRule(transition.to.predicate, next as Row);\n if (toResult !== true)\n return { ok: false, reason: { kind: 'no-to', to: reasonString(toResult) } };\n\n if (denies(authorize, basePermission, record as Row, actor))\n return { ok: false, reason: { kind: 'unauthorized', authz: 'action' } };\n if (denies(authorize, transition.from.permission, record as Row, actor))\n return { ok: false, reason: { kind: 'unauthorized', authz: 'from' } };\n if (denies(authorize, transition.to.permission, next as Row, actor))\n return { ok: false, reason: { kind: 'unauthorized', authz: 'to' } };\n\n return { ok: true, path: transition };\n};\n","import type { Reason } from './types';\n\n/** Build a human-readable message from a structured {@link Reason} (logs / UI / error bodies). */\nexport const describe = (reason: Reason): string => {\n switch (reason.kind) {\n case 'no-from':\n return reason.from ?? 'transition is not available from the current state';\n case 'no-to':\n return reason.to ?? 'the resulting state is not a valid target';\n case 'unauthorized':\n return reason.authz\n ? `not authorized (${reason.authz}-level permission denied)`\n : 'not authorized';\n default: {\n // exhaustiveness guard: a new FailureKind must be handled here, not silently return undefined\n const _exhaustive: never = reason.kind;\n return _exhaustive;\n }\n }\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport type { ActionRule, Actor, Authorize, Row } from '../types';\nimport type { RebacOptions, RebacSchema } from './types';\n\ntype Context = {\n schema: RebacSchema;\n resolveModel?: (model: string, relationSegment: string) => string;\n isSuperadmin?: (actor: Actor) => boolean;\n};\n\nconst evaluate = (\n ctx: Context,\n model: string,\n record: Row,\n actor: Actor,\n rule: ActionRule,\n visited: Set<string>,\n): boolean => {\n if (ctx.isSuperadmin?.(actor)) return true;\n if (rule === null) return false;\n\n // string → delegate to the named action on this model, additively merged with any per-row override.\n if (typeof rule === 'string') {\n const schemaRule = ctx.schema[model]?.actions[rule] ?? null;\n const rowRules = record.permissionRules as Record<string, ActionRule> | null | undefined;\n const rowRule = rowRules?.[rule];\n const merged: ActionRule = rowRule !== undefined ? { any: [schemaRule, rowRule] } : schemaRule;\n return evaluate(ctx, model, record, actor, merged, visited);\n }\n\n // { rel, action } → walk the relation (dot-paths supported), then check `action` on the target.\n if ('rel' in rule && 'action' in rule) {\n const segments = rule.rel.split('.');\n let current: Row = record;\n let currentModel = model;\n for (const segment of segments) {\n const related = current[segment] as Row | null | undefined;\n if (!related) return false;\n currentModel = ctx.resolveModel ? ctx.resolveModel(currentModel, segment) : segment;\n current = related;\n }\n const key = `${currentModel}:${String(current.id)}:${rule.action}`;\n if (visited.has(key)) throw new Error(`Cycle detected in permission graph: ${key}`);\n visited.add(key);\n return evaluate(ctx, currentModel, current, actor, rule.action, visited);\n }\n\n // { self } → record[field] matches the current actor.\n if ('self' in rule) {\n const actorId = actor?.id ?? null;\n return actorId !== null && record[rule.self] === actorId;\n }\n\n // { rule } → ABAC predicate (json-rules) over the record.\n if ('rule' in rule) return checkRule(rule.rule, record) === true;\n\n // Fork `visited` per branch — parallel paths through any/all aren't cycles.\n if ('any' in rule)\n return rule.any.some((sub) => evaluate(ctx, model, record, actor, sub, new Set(visited)));\n if ('all' in rule)\n return rule.all.every((sub) => evaluate(ctx, model, record, actor, sub, new Set(visited)));\n\n return false;\n};\n\n/**\n * A reference rebac evaluator — one implementation of the injected {@link Authorize} seam,\n * bound to a single `model`. Faithful to `@template/permissions`' `rebac/check` (string-delegate,\n * relation walk with cycle detection, self, json-rules `{ rule }`, any/all, per-row\n * `permissionRules` override) but standalone. Swap it for a richer authorizer in production;\n * this is slated to graduate into `@inixiative/permissions`.\n */\nexport const makeRebacAuthorize = (options: RebacOptions & { model: string }): Authorize => {\n const { model, ...rest } = options;\n return (rule, record, actor) => evaluate(rest, model, record, actor, rule, new Set());\n};\n\n/** Curried form: `createRebac({ schema })(model)` → an {@link Authorize} for that model. */\nexport const createRebac =\n (options: RebacOptions) =>\n (model: string): Authorize =>\n makeRebacAuthorize({ ...options, model });\n","import { check as checkRule, toPrisma } from '@inixiative/json-rules';\nimport { checkTransition } from './check';\nimport type {\n Action,\n AuthorizeOptions,\n CheckOptions,\n CheckResult,\n PathFailure,\n Reason,\n Row,\n TransitionMap,\n} from './types';\n\nconst getAction = (map: TransitionMap, model: string, verb: string): Action => {\n const action = map[model]?.[verb];\n if (!action) throw new Error(`transition: no action \"${verb}\" registered on model \"${model}\"`);\n return action;\n};\n\n// Pick the most-progressed failure across an action's paths:\n// unauthorized (a legal edge existed but authz denied) → 403\n// no-to (from matched, target invalid) → 409\n// no-from (no edge even starts here) → 409\nconst aggregate = (failures: Reason[]): Reason => {\n const paths: PathFailure[] = failures.map(({ kind: _kind, paths: _paths, ...rest }) => rest);\n const pick = (kind: Reason['kind']) => failures.find((failure) => failure.kind === kind);\n const chosen = pick('unauthorized') ?? pick('no-to') ?? pick('no-from');\n if (!chosen) return { kind: 'no-from', paths };\n const { paths: _omit, ...representative } = chosen;\n return { ...representative, paths };\n};\n\n/**\n * Authoritative check: the FIRST path whose `from` matches the current record, whose `to`\n * matches the merged record, and whose permissions all pass, wins. If none pass, returns the\n * aggregated structured failure (see {@link aggregate}).\n */\nexport const check = (\n map: TransitionMap,\n model: string,\n verb: string,\n record: Row,\n changes: Row = {},\n options: AuthorizeOptions = {},\n): CheckResult => {\n const action = getAction(map, model, verb);\n const opts: CheckOptions = { ...options, basePermission: action.permission };\n\n const failures: Reason[] = [];\n for (const path of action.paths) {\n const result = checkTransition(path, record, changes, opts);\n if (result.ok) return result;\n failures.push(result.reason);\n }\n return { ok: false, reason: aggregate(failures) };\n};\n\n/**\n * Affordance hint: which verbs are offerable from `record` right now. Evaluates ONLY the\n * `from` side (predicate + `action`/`from` permission against the current record) — `to` needs\n * the merged record, which doesn't exist without proposed changes, so it defers to {@link check}.\n */\nexport const available = (\n map: TransitionMap,\n model: string,\n record: Row,\n options: AuthorizeOptions = {},\n): string[] => {\n const actions = map[model];\n if (!actions) return [];\n const { actor, authorize } = options;\n\n const allows = (rule: Action['permission'], rec: Row): boolean =>\n !authorize || rule === undefined || authorize(rule, rec, actor);\n\n return Object.entries(actions)\n .filter(([, action]) =>\n action.paths.some(\n (path) =>\n checkRule(path.from.predicate, record) === true &&\n allows(action.permission, record) &&\n allows(path.from.permission, record),\n ),\n )\n .map(([verb]) => verb);\n};\n\n/**\n * Set query: one OR'd Prisma `where` matching every record currently eligible for `verb`\n * (the union of all its paths' `from` predicates). Empty action → match-nothing.\n */\nexport const eligible = (map: TransitionMap, model: string, verb: string): Row => {\n const action = getAction(map, model, verb);\n const { steps } = toPrisma({ any: action.paths.map((path) => path.from.predicate) });\n // json-rules guarantees the last step is the WhereStep. Assert it loudly rather than cast-and-swallow:\n // a silent `{}` fallback would mean match-EVERYTHING — the dangerous inverse of the intended\n // match-nothing — if a future json-rules emits a trailing non-where step or multi-step relation refs.\n const last = steps[steps.length - 1] as { operation?: string; where?: Row } | undefined;\n if (last?.operation !== 'where' || last.where === undefined)\n throw new Error('transition: expected a terminal WhereStep from toPrisma; got none');\n return last.where;\n};\n","import { isSerializableMerge } from './merge';\nimport type { Transition } from './types';\n\n/**\n * Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?\n *\n * Predicates (json-rules) and permissions (ActionRule) are always plain JSON; the only\n * non-data escape hatch is a `to.merge` callback. So serializability reduces to the merge.\n */\nexport const isSerializable = (transition: Transition): boolean =>\n isSerializableMerge(transition.to.merge);\n","import {\n type Condition,\n checkRuleAgainstLens,\n type Lens,\n type LensNarrowing,\n validateRule,\n} from '@inixiative/json-rules';\nimport { isSerializableMerge } from './merge';\nimport type { ActionRule, Merge, Side, ToSide, Transition } from './types';\n\nexport type ValidationIssue = { path: string; message: string };\nexport type ValidationResult = { ok: boolean; errors: ValidationIssue[] };\n\nexport type ValidateOptions = {\n /** Optional field/relation allowlist; passed through to json-rules lens validation per predicate. */\n lens?: Lens | LensNarrowing;\n /** Reject callback merges (use when the transition must be persistable / tenant-configured). */\n requireSerializable?: boolean;\n};\n\nconst MERGE_KEYWORDS = new Set(['spread', 'deepMerge']);\nconst ARRAY_KINDS = new Set(['append', 'appendUnique']);\n\nconst validatePredicate = (\n predicate: Condition,\n errors: ValidationIssue[],\n path: string,\n lens?: Lens | LensNarrowing,\n): void => {\n const result = validateRule(predicate);\n for (const issue of result.errors)\n errors.push({ path: `${path}.${issue.path}`, message: issue.message });\n if (lens) {\n const lensCheck = checkRuleAgainstLens(predicate, lens);\n for (const violation of lensCheck.violations)\n errors.push({ path: `${path}.${violation.path}`, message: violation.reason });\n }\n};\n\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined || rule === null || typeof rule === 'string') return;\n if ('rule' in rule) {\n const result = validateRule(rule.rule);\n for (const issue of result.errors)\n errors.push({ path: `${path}.rule.${issue.path}`, message: issue.message });\n return;\n }\n if ('rel' in rule) {\n if (!rule.rel || !rule.action)\n errors.push({ path, message: 'rel-rule requires non-empty `rel` and `action`' });\n return;\n }\n if ('self' in rule) {\n if (!rule.self) errors.push({ path, message: 'self-rule requires a non-empty field name' });\n return;\n }\n if ('any' in rule) {\n rule.any.forEach((sub, i) => {\n validatePermission(sub, errors, `${path}.any[${i}]`);\n });\n return;\n }\n if ('all' in rule) {\n rule.all.forEach((sub, i) => {\n validatePermission(sub, errors, `${path}.all[${i}]`);\n });\n return;\n }\n errors.push({ path, message: 'unrecognized ActionRule shape' });\n};\n\nconst validateMerge = (merge: Merge | undefined, errors: ValidationIssue[], path: string): void => {\n if (merge === undefined || typeof merge === 'function') return;\n if (typeof merge === 'string') {\n if (!MERGE_KEYWORDS.has(merge))\n errors.push({ path, message: `unknown merge strategy \"${merge}\"` });\n return;\n }\n if (!ARRAY_KINDS.has(merge.kind))\n errors.push({ path, message: `unknown merge kind \"${merge.kind}\"` });\n else if (!merge.path) errors.push({ path, message: `merge \"${merge.kind}\" requires a \\`path\\`` });\n};\n\nconst validateSide = (\n side: Side | ToSide,\n errors: ValidationIssue[],\n path: string,\n options: ValidateOptions,\n): void => {\n validatePredicate(side.predicate, errors, `${path}.predicate`, options.lens);\n validatePermission(side.permission, errors, `${path}.permission`);\n if (side.requires !== undefined && (typeof side.requires !== 'object' || side.requires === null))\n errors.push({\n path: `${path}.requires`,\n message: '`requires` must be a Prisma-include-shaped object',\n });\n if ('merge' in side) validateMerge(side.merge, errors, `${path}.merge`);\n};\n\n/**\n * Authoring validation for a single transition — run on save before persisting a tenant config.\n * Predicate validity delegates to json-rules (`validateRule`, plus `checkRuleAgainstLens` when a\n * `lens` is supplied for field/relation scoping); merge strategy and permission shape are checked here.\n */\nexport const validateTransition = (\n transition: Transition,\n options: ValidateOptions = {},\n): ValidationResult => {\n const errors: ValidationIssue[] = [];\n validateSide(transition.from, errors, 'from', options);\n validateSide(transition.to, errors, 'to', options);\n if (options.requireSerializable && !isSerializableMerge(transition.to.merge))\n errors.push({\n path: 'to.merge',\n message: 'callback merge is not serializable; use a keyword strategy',\n });\n return { ok: errors.length === 0, errors };\n};\n"]}
1
+ {"version":3,"sources":["../src/merge.ts","../src/check.ts","../src/describe.ts","../src/rebac/authorize.ts","../src/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["toArray","value","replaceArrays","_target","source","isSerializableMerge","merge","applyMerge","record","changes","strategy","mergeWith","cloneDeep","kind","path","base","merged","get","set","uniqWith","isEqual","predicateReason","result","denies","authorize","rule","actor","checkPath","transition","options","next","from","fromPredicate","checkRule","to","toPredicate","reason","describePath","segs","describe","i","evaluate","ctx","model","visited","schemaRule","rowRule","segments","current","currentModel","segment","related","key","actorId","sub","makeRebacAuthorize","rest","createRebac","getAction","rules","resource","action","found","checkTransition","paths","available","actions","allows","rec","eligible","steps","toPrisma","last","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","predicate","errors","lens","validateRule","issue","lensCheck","checkRuleAgainstLens","violation","validatePermission","validateMerge","validateSide","side","validateTransition"],"mappings":"2JAGA,IAAMA,CAAAA,CAAWC,CAAAA,EACf,KAAA,CAAM,OAAA,CAAQA,CAAK,EAAIA,CAAAA,CAAQA,CAAAA,GAAU,MAAA,CAAY,GAAK,CAACA,CAAK,CAAA,CAG5DC,CAAAA,CAAgB,CAACC,CAAAA,CAAkBC,CAAAA,GACvC,KAAA,CAAM,OAAA,CAAQA,CAAM,CAAA,CAAIA,CAAAA,CAAS,MAAA,CAGtBC,EAAuBC,CAAAA,EAA2B,OAAOA,CAAAA,EAAU,UAAA,CAWnEC,EAAa,CACxBD,CAAAA,CACAE,CAAAA,CACAC,CAAAA,CAAsB,EAAC,GACjB,CACN,GAAI,OAAOH,GAAU,UAAA,CAAY,OAAOA,CAAAA,CAAME,CAAAA,CAAQC,CAAO,CAAA,CAE7D,IAAMC,CAAAA,CAA0BJ,CAAAA,EAAS,SAEzC,GAAII,CAAAA,GAAa,QAAA,CAAU,OAAO,CAAE,GAAGF,CAAAA,CAA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CAAAA,CAAQ,CAAA,EAAGhE,CAAI,aAAce,CAAAA,CAAQ,IAAI,CAAA,CAC3EwD,CAAAA,CAAmBG,EAAK,UAAA,CAAYV,CAAAA,CAAQ,CAAA,EAAGhE,CAAI,aAAa,CAAA,CAC5D0E,CAAAA,CAAK,QAAA,GAAa,MAAA,GAAc,OAAOA,CAAAA,CAAK,QAAA,EAAa,QAAA,EAAYA,CAAAA,CAAK,QAAA,GAAa,IAAA,CAAA,EACzFV,CAAAA,CAAO,IAAA,CAAK,CACV,IAAA,CAAM,CAAA,EAAGhE,CAAI,CAAA,SAAA,CAAA,CACb,QAAS,mDACX,CAAC,CAAA,CACC,OAAA,GAAW0E,GAAMF,CAAAA,CAAcE,CAAAA,CAAK,KAAA,CAAOV,CAAAA,CAAQ,GAAGhE,CAAI,CAAA,MAAA,CAAQ,EACxE,CAAA,CAOa2E,GAAqB,CAChC7D,CAAAA,CACAC,CAAAA,CAA2B,KACN,CACrB,IAAMiD,CAAAA,CAA4B,GAClC,OAAAS,CAAAA,CAAa3D,CAAAA,CAAW,IAAA,CAAMkD,CAAAA,CAAQ,MAAA,CAAQjD,CAAO,CAAA,CACrD0D,EAAa3D,CAAAA,CAAW,EAAA,CAAIkD,CAAAA,CAAQ,IAAA,CAAMjD,CAAO,CAAA,CAC7CA,CAAAA,CAAQ,mBAAA,EAAuB,CAACxB,EAAoBuB,CAAAA,CAAW,EAAA,CAAG,KAAK,CAAA,EACzEkD,EAAO,IAAA,CAAK,CACV,IAAA,CAAM,UAAA,CACN,QAAS,4DACX,CAAC,CAAA,CACI,CAAE,GAAIA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAAAA,CAAO,CAC3C","file":"index.js","sourcesContent":["import { cloneDeep, get, isEqual, mergeWith, set, uniqWith } from 'lodash-es';\nimport type { Merge, MergeStrategy, Row } from './types';\n\nconst toArray = (value: unknown): unknown[] =>\n Array.isArray(value) ? value : value === undefined ? [] : [value];\n\n// deepMerge replaces arrays wholesale rather than index-merging them (the intuitive default).\nconst replaceArrays = (_target: unknown, source: unknown): unknown[] | undefined =>\n Array.isArray(source) ? source : undefined;\n\n/** A transition is persistable iff its merge is absent or a keyword strategy (callbacks are not). */\nexport const isSerializableMerge = (merge?: Merge): boolean => typeof merge !== 'function';\n\n/**\n * Produce the resulting record from a current record + proposed changes.\n *\n * - `spread` (default) — shallow overwrite (`{ ...record, ...changes }`)\n * - `deepMerge` — recursive object merge, arrays replaced\n * - `{ kind: 'append', path }` — concat `changes[path]` onto `record[path]`\n * - `{ kind: 'appendUnique', path }` — append + dedupe (deep equality)\n * - a callback — full power, not serializable\n */\nexport const applyMerge = <R extends Row>(\n merge: Merge<R> | undefined,\n record: R,\n changes: Partial<R> = {},\n): R => {\n if (typeof merge === 'function') return merge(record, changes);\n\n const strategy: MergeStrategy = merge ?? 'spread';\n\n if (strategy === 'spread') return { ...record, ...changes };\n // clone BOTH inputs: mergeWith assigns nested objects/arrays from `changes` by reference, which\n // would alias the caller's `changes` into the returned record (a mutation footgun for a pure guard).\n if (strategy === 'deepMerge')\n return mergeWith(cloneDeep(record), cloneDeep(changes), replaceArrays);\n\n // field-scoped array strategies: spread the rest of `changes`, then concat at `path`.\n const { kind, path } = strategy;\n const base = cloneDeep({ ...record, ...changes }) as R;\n const merged = [...toArray(get(record, path)), ...toArray(get(changes, path))];\n set(base as Row, path, kind === 'appendUnique' ? uniqWith(merged, isEqual) : merged);\n return base;\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport { applyMerge } from './merge';\nimport type {\n ActionRule,\n Actor,\n Authorize,\n AuthorizeOptions,\n PathReason,\n Row,\n SideReason,\n Transition,\n} from './types';\n\nconst predicateReason = (result: boolean | string): string =>\n typeof result === 'string' ? result : 'predicate not satisfied';\n\n/**\n * Does this permission DENY?\n * - no authorizer injected → can't deny (legality-only mode)\n * - `undefined` rule → permission absent → open → can't deny\n * - any other rule (incl. `null` = terminal deny) → delegate to the authorizer\n */\nconst denies = (\n authorize: Authorize | undefined,\n rule: ActionRule | undefined,\n record: Row,\n actor: Actor,\n): boolean => {\n if (!authorize || rule === undefined) return false;\n return !authorize(rule, record, actor);\n};\n\n/**\n * The kernel: evaluate one atomic edge. Reports every failure rather than short-circuiting —\n * `from`/`to` and predicate/permission are independent slots — so a caller sees the whole\n * picture. `from.*` reads the current `record`, `to.*` reads the merged `next` record. Returns\n * `true` when the edge is allowed, else the {@link PathReason}. Omit `authorize` for legality only.\n */\nexport const checkPath = <R extends Row>(\n transition: Transition<R>,\n record: R,\n changes: Partial<R> = {},\n options: AuthorizeOptions = {},\n): true | PathReason => {\n const { actor, authorize } = options;\n const next = applyMerge(transition.to.merge, record, changes);\n\n const from: SideReason = {};\n const fromPredicate = checkRule(transition.from.predicate, record as Row);\n if (fromPredicate !== true) from.predicate = predicateReason(fromPredicate);\n if (denies(authorize, transition.from.permission, record as Row, actor))\n from.permission = 'not authorized';\n\n const to: SideReason = {};\n const toPredicate = checkRule(transition.to.predicate, next as Row);\n if (toPredicate !== true) to.predicate = predicateReason(toPredicate);\n if (denies(authorize, transition.to.permission, next as Row, actor))\n to.permission = 'not authorized';\n\n const reason: PathReason = {};\n if (from.predicate || from.permission) reason.from = from;\n if (to.predicate || to.permission) reason.to = to;\n return reason.from || reason.to ? reason : true;\n};\n","import type { PathReason, Reason } from './types';\n\nconst describePath = (path: PathReason): string => {\n const segs: string[] = [];\n if (path.from?.predicate) segs.push(`from: ${path.from.predicate}`);\n if (path.from?.permission) segs.push(`from: ${path.from.permission}`);\n if (path.to?.predicate) segs.push(`to: ${path.to.predicate}`);\n if (path.to?.permission) segs.push(`to: ${path.to.permission}`);\n return segs.join('; ') || 'unknown';\n};\n\n/** Build a human-readable message from a structured {@link Reason} (logs / UI / error bodies). */\nexport const describe = (reason: Reason): string => {\n if (reason.paths.length === 0) return 'no transition path available';\n if (reason.paths.length === 1) return describePath(reason.paths[0]);\n return reason.paths.map((path, i) => `path ${i}: ${describePath(path)}`).join(' | ');\n};\n","import { check as checkRule } from '@inixiative/json-rules';\nimport type { ActionRule, Actor, Authorize, Row } from '../types';\nimport type { RebacOptions, RebacSchema } from './types';\n\ntype Context = {\n schema: RebacSchema;\n resolveModel?: (model: string, relationSegment: string) => string;\n isSuperadmin?: (actor: Actor) => boolean;\n};\n\nconst evaluate = (\n ctx: Context,\n model: string,\n record: Row,\n actor: Actor,\n rule: ActionRule,\n visited: Set<string>,\n): boolean => {\n if (ctx.isSuperadmin?.(actor)) return true;\n if (rule === null) return false;\n\n // string → delegate to the named action on this model, additively merged with any per-row override.\n if (typeof rule === 'string') {\n const schemaRule = ctx.schema[model]?.actions[rule] ?? null;\n const rowRules = record.permissionRules as Record<string, ActionRule> | null | undefined;\n const rowRule = rowRules?.[rule];\n const merged: ActionRule = rowRule !== undefined ? { any: [schemaRule, rowRule] } : schemaRule;\n return evaluate(ctx, model, record, actor, merged, visited);\n }\n\n // { rel, action } → walk the relation (dot-paths supported), then check `action` on the target.\n if ('rel' in rule && 'action' in rule) {\n const segments = rule.rel.split('.');\n let current: Row = record;\n let currentModel = model;\n for (const segment of segments) {\n const related = current[segment] as Row | null | undefined;\n if (!related) return false;\n currentModel = ctx.resolveModel ? ctx.resolveModel(currentModel, segment) : segment;\n current = related;\n }\n const key = `${currentModel}:${String(current.id)}:${rule.action}`;\n if (visited.has(key)) throw new Error(`Cycle detected in permission graph: ${key}`);\n visited.add(key);\n return evaluate(ctx, currentModel, current, actor, rule.action, visited);\n }\n\n // { self } → record[field] matches the current actor.\n if ('self' in rule) {\n const actorId = actor?.id ?? null;\n return actorId !== null && record[rule.self] === actorId;\n }\n\n // { rule } → ABAC predicate (json-rules) over the record.\n if ('rule' in rule) return checkRule(rule.rule, record) === true;\n\n // Fork `visited` per branch — parallel paths through any/all aren't cycles.\n if ('any' in rule)\n return rule.any.some((sub) => evaluate(ctx, model, record, actor, sub, new Set(visited)));\n if ('all' in rule)\n return rule.all.every((sub) => evaluate(ctx, model, record, actor, sub, new Set(visited)));\n\n return false;\n};\n\n/**\n * A reference rebac evaluator — one implementation of the injected {@link Authorize} seam,\n * bound to a single `model`. Faithful to `@template/permissions`' `rebac/check` (string-delegate,\n * relation walk with cycle detection, self, json-rules `{ rule }`, any/all, per-row\n * `permissionRules` override) but standalone. Swap it for a richer authorizer in production;\n * this is slated to graduate into `@inixiative/permissions`.\n */\nexport const makeRebacAuthorize = (options: RebacOptions & { model: string }): Authorize => {\n const { model, ...rest } = options;\n return (rule, record, actor) => evaluate(rest, model, record, actor, rule, new Set());\n};\n\n/** Curried form: `createRebac({ schema })(model)` → an {@link Authorize} for that model. */\nexport const createRebac =\n (options: RebacOptions) =>\n (model: string): Authorize =>\n makeRebacAuthorize({ ...options, model });\n","import { check as checkRule, toPrisma } from '@inixiative/json-rules';\nimport { checkPath } from './check';\nimport type {\n Action,\n ActionRule,\n AuthorizeOptions,\n CheckResult,\n PathReason,\n Row,\n TransitionMap,\n} from './types';\n\nconst getAction = (rules: TransitionMap, resource: string, action: string): Action => {\n const found = rules[resource]?.[action];\n if (!found)\n throw new Error(`transition: no action \"${action}\" registered on resource \"${resource}\"`);\n return found;\n};\n\n/**\n * Authoritative check: the FIRST path whose `from` matches the current record, whose `to` matches\n * the merged record, and whose permissions all pass, wins → `true`. If none pass, returns a\n * {@link Reason} with one {@link PathReason} per candidate path tried.\n *\n * `resource` is the (map-qualified) key into the map — e.g. `db:Inquiry`. Cross-source `permission`\n * checks are handled by the injected {@link Authorize} (wire it to a bridge-aware rebac check, bound\n * to this resource); a `predicate` that reads a bridged relation expects a stitched record.\n */\nexport const checkTransition = (\n rules: TransitionMap,\n resource: string,\n action: string,\n record: Row,\n changes: Row = {},\n options: AuthorizeOptions = {},\n): CheckResult => {\n const found = getAction(rules, resource, action);\n const paths: PathReason[] = [];\n for (const path of found.paths) {\n const result = checkPath(path, record, changes, options);\n if (result === true) return true;\n paths.push(result);\n }\n return { paths };\n};\n\n/**\n * Affordance hint: which actions are offerable from `record` right now. Evaluates ONLY the `from`\n * side (predicate + `from` permission against the current record) — `to` needs the merged record,\n * which doesn't exist without proposed changes, so it defers to {@link checkTransition}.\n */\nexport const available = (\n rules: TransitionMap,\n resource: string,\n record: Row,\n options: AuthorizeOptions = {},\n): string[] => {\n const actions = rules[resource];\n if (!actions) return [];\n const { actor, authorize } = options;\n\n const allows = (rule: ActionRule | undefined, rec: Row): boolean =>\n !authorize || rule === undefined || authorize(rule, rec, actor);\n\n return Object.entries(actions)\n .filter(([, action]) =>\n action.paths.some(\n (path) =>\n checkRule(path.from.predicate, record) === true && allows(path.from.permission, record),\n ),\n )\n .map(([action]) => action);\n};\n\n/**\n * Set query: one OR'd Prisma `where` matching every record currently eligible for `action`\n * (the union of all its paths' `from` predicates). Empty action → match-nothing.\n */\nexport const eligible = (rules: TransitionMap, resource: string, action: string): Row => {\n const found = getAction(rules, resource, action);\n const { steps } = toPrisma({ any: found.paths.map((path) => path.from.predicate) });\n // json-rules guarantees the last step is the WhereStep. Assert it loudly rather than cast-and-swallow:\n // a silent `{}` fallback would mean match-EVERYTHING — the dangerous inverse of match-nothing.\n const last = steps[steps.length - 1] as { operation?: string; where?: Row } | undefined;\n if (last?.operation !== 'where' || last.where === undefined)\n throw new Error('transition: expected a terminal WhereStep from toPrisma; got none');\n return last.where;\n};\n","import { isSerializableMerge } from './merge';\nimport type { Transition } from './types';\n\n/**\n * Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?\n *\n * Predicates (json-rules) and permissions (ActionRule) are always plain JSON; the only\n * non-data escape hatch is a `to.merge` callback. So serializability reduces to the merge.\n */\nexport const isSerializable = (transition: Transition): boolean =>\n isSerializableMerge(transition.to.merge);\n","import {\n type Condition,\n checkRuleAgainstLens,\n type Lens,\n type LensNarrowing,\n validateRule,\n} from '@inixiative/json-rules';\nimport { isSerializableMerge } from './merge';\nimport type { ActionRule, Merge, Side, ToSide, Transition } from './types';\n\nexport type ValidationIssue = { path: string; message: string };\nexport type ValidationResult = { ok: boolean; errors: ValidationIssue[] };\n\nexport type ValidateOptions = {\n /** Optional field/relation allowlist; passed through to json-rules lens validation per predicate. */\n lens?: Lens | LensNarrowing;\n /** Reject callback merges (use when the transition must be persistable / tenant-configured). */\n requireSerializable?: boolean;\n};\n\nconst MERGE_KEYWORDS = new Set(['spread', 'deepMerge']);\nconst ARRAY_KINDS = new Set(['append', 'appendUnique']);\n\nconst validatePredicate = (\n predicate: Condition,\n errors: ValidationIssue[],\n path: string,\n lens?: Lens | LensNarrowing,\n): void => {\n const result = validateRule(predicate);\n for (const issue of result.errors)\n errors.push({ path: `${path}.${issue.path}`, message: issue.message });\n if (lens) {\n const lensCheck = checkRuleAgainstLens(predicate, lens);\n for (const violation of lensCheck.violations)\n errors.push({ path: `${path}.${violation.path}`, message: violation.reason });\n }\n};\n\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined || rule === null || typeof rule === 'string') return;\n if ('rule' in rule) {\n const result = validateRule(rule.rule);\n for (const issue of result.errors)\n errors.push({ path: `${path}.rule.${issue.path}`, message: issue.message });\n return;\n }\n if ('rel' in rule) {\n if (!rule.rel || !rule.action)\n errors.push({ path, message: 'rel-rule requires non-empty `rel` and `action`' });\n return;\n }\n if ('self' in rule) {\n if (!rule.self) errors.push({ path, message: 'self-rule requires a non-empty field name' });\n return;\n }\n if ('any' in rule) {\n rule.any.forEach((sub, i) => {\n validatePermission(sub, errors, `${path}.any[${i}]`);\n });\n return;\n }\n if ('all' in rule) {\n rule.all.forEach((sub, i) => {\n validatePermission(sub, errors, `${path}.all[${i}]`);\n });\n return;\n }\n errors.push({ path, message: 'unrecognized ActionRule shape' });\n};\n\nconst validateMerge = (merge: Merge | undefined, errors: ValidationIssue[], path: string): void => {\n if (merge === undefined || typeof merge === 'function') return;\n if (typeof merge === 'string') {\n if (!MERGE_KEYWORDS.has(merge))\n errors.push({ path, message: `unknown merge strategy \"${merge}\"` });\n return;\n }\n if (!ARRAY_KINDS.has(merge.kind))\n errors.push({ path, message: `unknown merge kind \"${merge.kind}\"` });\n else if (!merge.path) errors.push({ path, message: `merge \"${merge.kind}\" requires a \\`path\\`` });\n};\n\nconst validateSide = (\n side: Side | ToSide,\n errors: ValidationIssue[],\n path: string,\n options: ValidateOptions,\n): void => {\n validatePredicate(side.predicate, errors, `${path}.predicate`, options.lens);\n validatePermission(side.permission, errors, `${path}.permission`);\n if (side.requires !== undefined && (typeof side.requires !== 'object' || side.requires === null))\n errors.push({\n path: `${path}.requires`,\n message: '`requires` must be a Prisma-include-shaped object',\n });\n if ('merge' in side) validateMerge(side.merge, errors, `${path}.merge`);\n};\n\n/**\n * Authoring validation for a single transition — run on save before persisting a tenant config.\n * Predicate validity delegates to json-rules (`validateRule`, plus `checkRuleAgainstLens` when a\n * `lens` is supplied for field/relation scoping); merge strategy and permission shape are checked here.\n */\nexport const validateTransition = (\n transition: Transition,\n options: ValidateOptions = {},\n): ValidationResult => {\n const errors: ValidationIssue[] = [];\n validateSide(transition.from, errors, 'from', options);\n validateSide(transition.to, errors, 'to', options);\n if (options.requireSerializable && !isSerializableMerge(transition.to.merge))\n errors.push({\n path: 'to.merge',\n message: 'callback merge is not serializable; use a keyword strategy',\n });\n return { ok: errors.length === 0, errors };\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inixiative/transitions",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "Declarative, serializable transition guard + affordance layer on top of @inixiative/json-rules",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -56,7 +56,7 @@
56
56
  }
57
57
  },
58
58
  "dependencies": {
59
- "@inixiative/json-rules": "^2.6.0",
59
+ "@inixiative/json-rules": "^2.10.0",
60
60
  "lodash-es": "^4.17.21"
61
61
  },
62
62
  "exports": {