@inixiative/transitions 0.0.2 → 0.1.0
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 +47 -22
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +49 -57
- package/dist/index.d.ts +49 -57
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +15 -11
package/README.md
CHANGED
|
@@ -17,11 +17,14 @@ no deploy to change a lifecycle).
|
|
|
17
17
|
## Model
|
|
18
18
|
|
|
19
19
|
```
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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.
|
|
@@ -37,7 +40,7 @@ concrete record, so there is no record-free action-level permission.
|
|
|
37
40
|
import { checkTransition } from '@inixiative/transitions';
|
|
38
41
|
|
|
39
42
|
const rules = {
|
|
40
|
-
|
|
43
|
+
'db:Inquiry': {
|
|
41
44
|
approve: {
|
|
42
45
|
paths: [
|
|
43
46
|
{
|
|
@@ -49,14 +52,14 @@ const rules = {
|
|
|
49
52
|
},
|
|
50
53
|
};
|
|
51
54
|
|
|
52
|
-
checkTransition(rules, '
|
|
55
|
+
checkTransition(rules, 'db:Inquiry', 'approve', { status: 'pending' }, { status: 'approved' });
|
|
53
56
|
// → true
|
|
54
57
|
|
|
55
|
-
checkTransition(rules, '
|
|
58
|
+
checkTransition(rules, 'db:Inquiry', 'approve', { status: 'approved' }, { status: 'approved' });
|
|
56
59
|
// → { paths: [{ from: { predicate: 'status must equal "pending"' } }] }
|
|
57
60
|
```
|
|
58
61
|
|
|
59
|
-
`checkTransition(rules,
|
|
62
|
+
`checkTransition(rules, resource, action, record, changes, { actor, authorize })` returns **`true`** when
|
|
60
63
|
allowed, else a structured **`Reason`** — never a bare bool:
|
|
61
64
|
|
|
62
65
|
```ts
|
|
@@ -77,14 +80,15 @@ else every path's `PathReason`.
|
|
|
77
80
|
## Permissions are injected (the seam)
|
|
78
81
|
|
|
79
82
|
The kernel never imports an authorization library. Per-side `permission` is a serializable
|
|
80
|
-
`ActionRule`
|
|
81
|
-
`
|
|
83
|
+
`ActionRule` re-exported straight from [`@inixiative/permissions`](https://github.com/inixiative/permissions)
|
|
84
|
+
(`string` delegation, `{ rel, action }`, `{ self }`, abac `{ rule }`, `any`/`all`, boolean terminals
|
|
85
|
+
`true`/`false`, `null`), and you inject an `authorize` callback to evaluate it:
|
|
82
86
|
|
|
83
87
|
```ts
|
|
84
|
-
import { checkTransition,
|
|
88
|
+
import { checkTransition, createAuthorize } from '@inixiative/transitions';
|
|
85
89
|
|
|
86
|
-
const authorize =
|
|
87
|
-
checkTransition(rules, '
|
|
90
|
+
const authorize = createAuthorize({ schema: rebacSchema })('db:Inquiry');
|
|
91
|
+
checkTransition(rules, 'db:Inquiry', 'approve', record, changes, { actor, authorize });
|
|
88
92
|
```
|
|
89
93
|
|
|
90
94
|
Effective authz ANDs the two side rules, each against the record it reads:
|
|
@@ -94,25 +98,44 @@ from.permission AND to.permission
|
|
|
94
98
|
(current record) (merged record)
|
|
95
99
|
```
|
|
96
100
|
|
|
97
|
-
Absent = open; `null` = terminal deny. Omit `authorize` to check legality only.
|
|
101
|
+
Absent = open; `null` (or `false`) = terminal deny. Omit `authorize` to check legality only.
|
|
102
|
+
|
|
103
|
+
### `createAuthorize` — the `@inixiative/permissions` adapter
|
|
104
|
+
|
|
105
|
+
Authorization is **not** reimplemented here. `createAuthorize` is a thin adapter that bridges
|
|
106
|
+
`@inixiative/permissions`' production rebac `check` onto the `Authorize` seam:
|
|
107
|
+
`createAuthorize(options)(resource)` returns an `Authorize` bound to a (map-qualified) `resource`.
|
|
108
|
+
permissions owns the whole evaluation — `string` delegation with **cycle detection**, intra-map `rel`
|
|
109
|
+
walks (via an injected `resolveRelation`), cross-map bridge walks, `{ self }`, abac `{ rule }`, boolean
|
|
110
|
+
terminals, `any`/`all`, and per-row `permissionRules` overrides. It speaks the same map-qualified
|
|
111
|
+
`resource` keys as this package.
|
|
98
112
|
|
|
99
|
-
|
|
113
|
+
```ts
|
|
114
|
+
import type { RebacSchema } from '@inixiative/permissions';
|
|
115
|
+
import { createAuthorize } from '@inixiative/transitions';
|
|
116
|
+
|
|
117
|
+
const schema: RebacSchema = { permissions: { 'db:Inquiry': { actions: { /* … */ } } } };
|
|
118
|
+
const authorize = createAuthorize({
|
|
119
|
+
schema,
|
|
120
|
+
resolveRelation, // optional; default: the relation segment name is the resource key
|
|
121
|
+
isSuperadmin, // optional; derived from the actor
|
|
122
|
+
})('db:Inquiry');
|
|
123
|
+
```
|
|
100
124
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
the transition core changes.
|
|
125
|
+
`options`: `schema` (permissions' `{ bridges?, permissions }`), optional `resolveRelation`,
|
|
126
|
+
`isSuperadmin`, and `data` (supplemental hydrated rows for bridge walks). A cyclic permission graph —
|
|
127
|
+
which permissions surfaces by throwing — is caught and denied (fail closed), so the guard terminates
|
|
128
|
+
cleanly.
|
|
106
129
|
|
|
107
130
|
## Affordance + set query
|
|
108
131
|
|
|
109
132
|
```ts
|
|
110
133
|
import { available, eligible } from '@inixiative/transitions';
|
|
111
134
|
|
|
112
|
-
available(rules, '
|
|
135
|
+
available(rules, 'db:Inquiry', record, { actor, authorize });
|
|
113
136
|
// → ['approve', 'reject', 'cancel'] (from-side only — `to` needs proposed changes, so it defers to checkTransition)
|
|
114
137
|
|
|
115
|
-
eligible(rules, '
|
|
138
|
+
eligible(rules, 'db:Inquiry', 'approve');
|
|
116
139
|
// → { OR: [{ status: { equals: 'pending' } }] } (Prisma where for "every record eligible for approve")
|
|
117
140
|
```
|
|
118
141
|
|
|
@@ -130,7 +153,9 @@ but not (`isSerializable(transition)` tells you which).
|
|
|
130
153
|
|
|
131
154
|
`validateTransition(t, { lens?, requireSerializable? })` validates predicates (via json-rules
|
|
132
155
|
`validateRule`, plus `checkRuleAgainstLens` when a `lens` scopes referenceable fields), merge
|
|
133
|
-
strategy, and permission shape — run it on
|
|
156
|
+
strategy, and permission shape (via `@inixiative/permissions`' zod `actionRuleSchema`) — run it on
|
|
157
|
+
save before persisting a tenant config. It returns structured `{ ok, errors }` (never throws), even on
|
|
158
|
+
malformed input.
|
|
134
159
|
|
|
135
160
|
## Not built yet (designed — see the plan)
|
|
136
161
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var jsonRules=require('@inixiative/json-rules'),lodashEs=require('lodash-es');var
|
|
1
|
+
'use strict';var permissions=require('@inixiative/permissions'),jsonRules=require('@inixiative/json-rules'),lodashEs=require('lodash-es'),actionRuleSchema=require('@inixiative/permissions/actionRuleSchema');var z=/Cycle detected/,P=(e,t)=>({check:()=>false,isSuperadmin:()=>t?.(e)??false,getUserId:()=>e?.id??null}),W=e=>{let t=e.resolveRelation??((i,n)=>n),o=permissions.createRebacCheck(t);return i=>(n,r,a)=>{let p=P(a,e.isSuperadmin),c={resource:i,record:r,data:e.data?.(r,a)};try{return o(p,e.schema,c,n)}catch(s){if(s instanceof Error&&z.test(s.message))return false;throw s}}};var R=e=>Array.isArray(e)?e:e===void 0?[]:[e],q=(e,t)=>Array.isArray(t)?t:void 0,f=e=>typeof e!="function",h=(e,t,o={})=>{if(typeof e=="function")return e(t,o);let i=e??"spread";if(i==="spread")return {...t,...o};if(i==="deepMerge")return lodashEs.mergeWith(lodashEs.cloneDeep(t),lodashEs.cloneDeep(o),q);let{kind:n,path:r}=i,a=lodashEs.cloneDeep({...t,...o}),p=[...R(lodashEs.get(t,r)),...R(lodashEs.get(o,r))];return lodashEs.set(a,r,n==="appendUnique"?lodashEs.uniqWith(p,lodashEs.isEqual):p),a};var y=e=>typeof e=="string"?e:"predicate not satisfied",A=(e,t,o,i)=>!e||t===void 0?false:!e(t,o,i),w=(e,t,o={},i={})=>{let{actor:n,authorize:r}=i,a=h(e.to.merge,t,o),p={},c=jsonRules.check(e.from.predicate,t);c!==true&&(p.predicate=y(c)),A(r,e.from.permission,t,n)&&(p.permission="not authorized");let s={},m=jsonRules.check(e.to.predicate,a);m!==true&&(s.predicate=y(m)),A(r,e.to.permission,a,n)&&(s.permission="not authorized");let u={};return (p.predicate||p.permission)&&(u.from=p),(s.predicate||s.permission)&&(u.to=s),u.from||u.to?u:true};var b=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"},J=e=>e.paths.length===0?"no transition path available":e.paths.length===1?b(e.paths[0]):e.paths.map((t,o)=>`path ${o}: ${b(t)}`).join(" | ");var k=(e,t,o)=>{let i=e[t]?.[o];if(!i)throw new Error(`transition: no action "${o}" registered on resource "${t}"`);return i},ee=(e,t,o,i,n={},r={})=>{let a=k(e,t,o),p=[];for(let c of a.paths){let s=w(c,i,n,r);if(s===true)return true;p.push(s);}return {paths:p}},te=(e,t,o,i={})=>{let n=e[t];if(!n)return [];let{actor:r,authorize:a}=i,p=(c,s)=>!a||c===void 0||a(c,s,r);return Object.entries(n).filter(([,c])=>c.paths.some(s=>jsonRules.check(s.from.predicate,o)===true&&p(s.from.permission,o))).map(([c])=>c)},oe=(e,t,o)=>{let i=k(e,t,o),{steps:n}=jsonRules.toPrisma({any:i.paths.map(r=>r.from.predicate)});return n[n.length-1].where};var re=e=>f(e.to.merge);var I=new Set(["spread","deepMerge"]),E=new Set(["append","appendUnique"]),N=(e,t,o,i)=>{if(e===void 0){t.push({path:o,message:"predicate is required"});return}let n=jsonRules.validateRule(e);for(let r of n.errors)t.push({path:`${o}.${r.path}`,message:r.message});if(i){let r=jsonRules.checkRuleAgainstLens(e,i);for(let a of r.violations)t.push({path:`${o}.${a.path}`,message:a.reason});}},_=(e,t,o)=>{if(e===void 0)return;let i=actionRuleSchema.actionRuleSchema.safeParse(e);if(!i.success)for(let n of i.error.issues)n.path.length===0?t.push({path:o,message:"unrecognized ActionRule shape"}):t.push({path:`${o}.${n.path.join(".")}`,message:n.message});},D=(e,t,o)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){I.has(e)||t.push({path:o,message:`unknown merge strategy "${e}"`});return}E.has(e.kind)?e.path||t.push({path:o,message:`merge "${e.kind}" requires a \`path\``}):t.push({path:o,message:`unknown merge kind "${e.kind}"`});}},x=(e,t,o,i)=>{if(e===null||typeof e!="object"){t.push({path:o,message:`\`${o}\` side is required`});return}N(e.predicate,t,`${o}.predicate`,i.lens),_(e.permission,t,`${o}.permission`),e.requires!==void 0&&(typeof e.requires!="object"||e.requires===null)&&t.push({path:`${o}.requires`,message:"`requires` must be a Prisma-include-shaped object"}),"merge"in e&&D(e.merge,t,`${o}.merge`);},ue=(e,t={})=>{let o=[];return x(e?.from,o,"from",t),x(e?.to,o,"to",t),t.requireSerializable&&!f(e?.to?.merge)&&o.push({path:"to.merge",message:"callback merge is not serializable; use a keyword strategy"}),{ok:o.length===0,errors:o}};exports.applyMerge=h;exports.available=te;exports.checkPath=w;exports.checkTransition=ee;exports.createAuthorize=W;exports.describe=J;exports.eligible=oe;exports.isSerializable=re;exports.isSerializableMerge=f;exports.validateTransition=ue;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.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","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","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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AAA,CAC3EuD,CAAAA,CAAmBG,EAAK,UAAA,CAAYV,CAAAA,CAAQ,CAAA,EAAG/D,CAAI,aAAa,CAAA,CAC5DyE,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,EAAG/D,CAAI,CAAA,SAAA,CAAA,CACb,QAAS,mDACX,CAAC,CAAA,CACC,OAAA,GAAWyE,GAAMF,CAAAA,CAAcE,CAAAA,CAAK,KAAA,CAAOV,CAAAA,CAAQ,GAAG/D,CAAI,CAAA,MAAA,CAAQ,EACxE,CAAA,CAOa0E,GAAqB,CAChC5D,CAAAA,CACAC,CAAAA,CAA2B,KACN,CACrB,IAAMgD,CAAAA,CAA4B,GAClC,OAAAS,CAAAA,CAAa1D,CAAAA,CAAW,IAAA,CAAMiD,CAAAA,CAAQ,MAAA,CAAQhD,CAAO,CAAA,CACrDyD,EAAa1D,CAAAA,CAAW,EAAA,CAAIiD,CAAAA,CAAQ,IAAA,CAAMhD,CAAO,CAAA,CAC7CA,CAAAA,CAAQ,mBAAA,EAAuB,CAACxB,EAAoBuB,CAAAA,CAAW,EAAA,CAAG,KAAK,CAAA,EACzEiD,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, model: string, action: string): Action => {\n const found = rules[model]?.[action];\n if (!found) throw new Error(`transition: no action \"${action}\" registered on model \"${model}\"`);\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 */\nexport const checkTransition = (\n rules: TransitionMap,\n model: string,\n action: string,\n record: Row,\n changes: Row = {},\n options: AuthorizeOptions = {},\n): CheckResult => {\n const found = getAction(rules, model, 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 model: string,\n record: Row,\n options: AuthorizeOptions = {},\n): string[] => {\n const actions = rules[model];\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, model: string, action: string): Row => {\n const found = getAction(rules, model, 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"]}
|
|
1
|
+
{"version":3,"sources":["../src/authorize.ts","../src/merge.ts","../src/check.ts","../src/describe.ts","../src/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["CYCLE","actorPermix","actor","isSuperadmin","createAuthorize","options","resolveRelation","_resource","segment","check","createRebacCheck","resource","rule","record","permix","subject","error","toArray","value","replaceArrays","_target","source","isSerializableMerge","merge","applyMerge","changes","strategy","mergeWith","cloneDeep","kind","path","base","merged","get","set","uniqWith","isEqual","predicateReason","result","denies","authorize","checkPath","transition","next","from","fromPredicate","checkRule","to","toPredicate","reason","describePath","segs","describe","i","getAction","rules","action","found","checkTransition","paths","available","actions","allows","rec","eligible","steps","toPrisma","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","predicate","errors","lens","validateRule","issue","lensCheck","checkRuleAgainstLens","violation","validatePermission","parsed","actionRuleSchema","validateMerge","validateSide","side","validateTransition"],"mappings":"+MAYA,IAAMA,CAAAA,CAAQ,gBAAA,CAwBRC,CAAAA,CAAc,CAACC,CAAAA,CAAcC,CAAAA,IAA0D,CAC3F,KAAA,CAAO,IAAM,KAAA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AA,CACN,OAAA,CAAS,4DACX,CAAC,CAAA,CACI,CAAE,EAAA,CAAIA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAAAA,CAAO,CAC3C","file":"index.cjs","sourcesContent":["import {\n type ActionRule,\n createRebacCheck,\n type PermixLike,\n type RebacSchema,\n type ResolveRelation,\n type Subject,\n} from '@inixiative/permissions';\nimport type { Actor, Authorize, Row } from './types';\n\n// permissions surfaces a cyclic permission graph by throwing; the transitions guard denies (fail\n// closed) so a misconfigured schema terminates cleanly instead of propagating out of the kernel.\nconst CYCLE = /Cycle detected/;\n\nexport type PermissionsAuthorizeOptions<R extends string = string> = {\n /** The permissions rebac schema: `{ bridges?, permissions }`. */\n schema: RebacSchema<R>;\n /**\n * Resolve a hydrated relation field to the resource it points at (the ORM-specific seam).\n * Default: the relation segment name doubles as the resource key. Cross-map bridges are resolved\n * by the engine from `schema.bridges`, not here.\n */\n resolveRelation?: ResolveRelation<R>;\n /** Superadmin bypass, derived from the actor; checked before any rule. */\n isSuperadmin?: (actor: Actor) => boolean;\n /**\n * Supplemental hydrated rows (`map:model → rows`) for bridge (cross-map) `rel` walks, derived from\n * the record + actor — the same shape `Subject.data` takes. Only consulted when a walk crosses a\n * bridge and a downstream action reads the far record's fields.\n */\n data?: (record: Row, actor: Actor) => Subject<R>['data'];\n};\n\n// The transitions seam carries no pre-granted (role-derived) permix state, so a direct permix grant\n// always misses and authorization is decided entirely by the schema. The actor supplies only its id\n// (for `{ self }`) and an optional superadmin bypass.\nconst actorPermix = (actor: Actor, isSuperadmin?: (actor: Actor) => boolean): PermixLike => ({\n check: () => false,\n isSuperadmin: () => isSuperadmin?.(actor) ?? false,\n getUserId: () => actor?.id ?? null,\n});\n\n/**\n * Bridge `@inixiative/permissions`' rebac `check` onto transitions' {@link Authorize} seam — the\n * production evaluator, injected, not reimplemented. `createAuthorize(options)(resource)` returns an\n * `Authorize` bound to a (map-qualified) `resource`; each call evaluates a per-side `permission`\n * rule against a concrete record + actor. permissions owns the evaluation (string delegation with\n * cycle detection, intra-map `rel` walks via `resolveRelation`, cross-map bridge walks, `{ self }`,\n * abac `{ rule }`, boolean terminals, `any`/`all`, per-row `permissionRules` overrides).\n */\nexport const createAuthorize = <R extends string = string>(\n options: PermissionsAuthorizeOptions<R>,\n): ((resource: R) => Authorize) => {\n const resolveRelation: ResolveRelation<R> =\n options.resolveRelation ?? ((_resource, segment) => segment as R);\n const check = createRebacCheck<R>(resolveRelation);\n\n return (resource: R): Authorize =>\n (rule, record, actor) => {\n const permix = actorPermix(actor, options.isSuperadmin);\n const subject: Subject<R> = { resource, record, data: options.data?.(record, actor) };\n try {\n return check(permix, options.schema, subject, rule as ActionRule);\n } catch (error) {\n if (error instanceof Error && CYCLE.test(error.message)) return false;\n throw error;\n }\n };\n};\n","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, 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 // toPrisma always terminates a plan in a WhereStep (and throws on count-based ops,\n // which would need a multi-step plan, since we pass no map/model). Trust that contract.\n const { steps } = toPrisma({ any: found.paths.map((path) => path.from.predicate) });\n return (steps[steps.length - 1] as { where: Row }).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 { actionRuleSchema } from '@inixiative/permissions/actionRuleSchema';\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 | undefined,\n errors: ValidationIssue[],\n path: string,\n lens?: Lens | LensNarrowing,\n): void => {\n if (predicate === undefined) {\n errors.push({ path, message: 'predicate is required' });\n return;\n }\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\n// Validate the whole ActionRule against `@inixiative/permissions`' zod schema — the single source of\n// truth for the algebra (boolean terminals, string delegation, `{ rel, action }`, `{ self }`, abac\n// `{ rule }`, `any`/`all`, `null`). A malformed rule yields a structured issue rather than throwing.\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined) return; // absent = open\n const parsed = actionRuleSchema.safeParse(rule);\n if (parsed.success) return;\n for (const issue of parsed.error.issues) {\n // A root union failure (zod reports an empty relative path) means none of the ActionRule shapes\n // matched; nested issues keep their zod path + message.\n if (issue.path.length === 0) {\n errors.push({ path, message: 'unrecognized ActionRule shape' });\n } else {\n errors.push({ path: `${path}.${issue.path.join('.')}`, message: issue.message });\n }\n }\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 | undefined,\n errors: ValidationIssue[],\n path: string,\n options: ValidateOptions,\n): void => {\n if (side === null || typeof side !== 'object') {\n errors.push({ path, message: `\\`${path}\\` side is required` });\n return;\n }\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 * Returns structured issues (never throws) on malformed input: predicate validity delegates to\n * json-rules (`validateRule`, plus `checkRuleAgainstLens` when a `lens` is supplied for\n * field/relation scoping); permission shape delegates to `@inixiative/permissions`' `actionRuleSchema`;\n * merge strategy is 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
|
@@ -1,30 +1,16 @@
|
|
|
1
|
+
import { ActionRule, RebacSchema, ResolveRelation, Subject } from '@inixiative/permissions';
|
|
2
|
+
export { ActionRule } from '@inixiative/permissions';
|
|
1
3
|
import { Condition, Lens, LensNarrowing } from '@inixiative/json-rules';
|
|
2
4
|
|
|
3
5
|
type Row = Record<string, unknown>;
|
|
4
|
-
|
|
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.
|
|
9
|
-
*/
|
|
10
|
-
type ActionRule = string | {
|
|
11
|
-
rel: string;
|
|
12
|
-
action: string;
|
|
13
|
-
} | {
|
|
14
|
-
self: string;
|
|
15
|
-
} | {
|
|
16
|
-
rule: Condition;
|
|
17
|
-
} | {
|
|
18
|
-
any: ActionRule[];
|
|
19
|
-
} | {
|
|
20
|
-
all: ActionRule[];
|
|
21
|
-
} | null;
|
|
6
|
+
|
|
22
7
|
type Actor = ({
|
|
23
8
|
id?: string | null;
|
|
24
9
|
} & Row) | null | undefined;
|
|
25
10
|
/**
|
|
26
|
-
* Injected permission evaluator.
|
|
27
|
-
* so the consumer closes over whatever its rebac needs (see {@link
|
|
11
|
+
* Injected permission evaluator. Resource-free: the kernel knows nothing about resources or schemas,
|
|
12
|
+
* so the consumer closes over whatever its rebac needs (see {@link createAuthorize}, the adapter
|
|
13
|
+
* over `@inixiative/permissions`).
|
|
28
14
|
*/
|
|
29
15
|
type Authorize = (rule: ActionRule, record: Row, actor: Actor) => boolean;
|
|
30
16
|
/** Serializable merge keywords (Mongo-flavored). Array strategies are field-scoped. */
|
|
@@ -66,7 +52,9 @@ type Action<R extends Row = Row> = {
|
|
|
66
52
|
paths: Transition<R>[];
|
|
67
53
|
label?: string;
|
|
68
54
|
};
|
|
69
|
-
/** `
|
|
55
|
+
/** `resource → action → Action`, where `resource` is the (map-qualified) key — e.g. `db:Inquiry`,
|
|
56
|
+
* matching `@inixiative/permissions`' rebac schema keys so a transition's `permission` resolves
|
|
57
|
+
* against the same resource identity. */
|
|
70
58
|
type TransitionMap = Record<string, Record<string, Action>>;
|
|
71
59
|
/** Why one side failed. Both keys are independent; either, both, or neither may be set. */
|
|
72
60
|
type SideReason = {
|
|
@@ -90,6 +78,34 @@ type AuthorizeOptions = {
|
|
|
90
78
|
authorize?: Authorize;
|
|
91
79
|
};
|
|
92
80
|
|
|
81
|
+
type PermissionsAuthorizeOptions<R extends string = string> = {
|
|
82
|
+
/** The permissions rebac schema: `{ bridges?, permissions }`. */
|
|
83
|
+
schema: RebacSchema<R>;
|
|
84
|
+
/**
|
|
85
|
+
* Resolve a hydrated relation field to the resource it points at (the ORM-specific seam).
|
|
86
|
+
* Default: the relation segment name doubles as the resource key. Cross-map bridges are resolved
|
|
87
|
+
* by the engine from `schema.bridges`, not here.
|
|
88
|
+
*/
|
|
89
|
+
resolveRelation?: ResolveRelation<R>;
|
|
90
|
+
/** Superadmin bypass, derived from the actor; checked before any rule. */
|
|
91
|
+
isSuperadmin?: (actor: Actor) => boolean;
|
|
92
|
+
/**
|
|
93
|
+
* Supplemental hydrated rows (`map:model → rows`) for bridge (cross-map) `rel` walks, derived from
|
|
94
|
+
* the record + actor — the same shape `Subject.data` takes. Only consulted when a walk crosses a
|
|
95
|
+
* bridge and a downstream action reads the far record's fields.
|
|
96
|
+
*/
|
|
97
|
+
data?: (record: Row, actor: Actor) => Subject<R>['data'];
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Bridge `@inixiative/permissions`' rebac `check` onto transitions' {@link Authorize} seam — the
|
|
101
|
+
* production evaluator, injected, not reimplemented. `createAuthorize(options)(resource)` returns an
|
|
102
|
+
* `Authorize` bound to a (map-qualified) `resource`; each call evaluates a per-side `permission`
|
|
103
|
+
* rule against a concrete record + actor. permissions owns the evaluation (string delegation with
|
|
104
|
+
* cycle detection, intra-map `rel` walks via `resolveRelation`, cross-map bridge walks, `{ self }`,
|
|
105
|
+
* abac `{ rule }`, boolean terminals, `any`/`all`, per-row `permissionRules` overrides).
|
|
106
|
+
*/
|
|
107
|
+
declare const createAuthorize: <R extends string = string>(options: PermissionsAuthorizeOptions<R>) => ((resource: R) => Authorize);
|
|
108
|
+
|
|
93
109
|
/**
|
|
94
110
|
* The kernel: evaluate one atomic edge. Reports every failure rather than short-circuiting —
|
|
95
111
|
* `from`/`to` and predicate/permission are independent slots — so a caller sees the whole
|
|
@@ -114,53 +130,27 @@ declare const isSerializableMerge: (merge?: Merge) => boolean;
|
|
|
114
130
|
*/
|
|
115
131
|
declare const applyMerge: <R extends Row>(merge: Merge<R> | undefined, record: R, changes?: Partial<R>) => R;
|
|
116
132
|
|
|
117
|
-
type ModelPermission = {
|
|
118
|
-
actions: Record<string, ActionRule>;
|
|
119
|
-
};
|
|
120
|
-
/** `model → { actions: { actionName → ActionRule } }`. Mirrors `@template/permissions` RebacSchema. */
|
|
121
|
-
type RebacSchema = Record<string, ModelPermission>;
|
|
122
|
-
type RebacOptions = {
|
|
123
|
-
schema: RebacSchema;
|
|
124
|
-
/**
|
|
125
|
-
* Resolve the model a relation points at, given the source model + relation segment.
|
|
126
|
-
* Default: the relation segment name doubles as the target model key. Supply this when your
|
|
127
|
-
* relation field names differ from your model names (the template binds this via prismaMap).
|
|
128
|
-
*/
|
|
129
|
-
resolveModel?: (model: string, relationSegment: string) => string;
|
|
130
|
-
/** Optional superadmin bypass, checked before any rule. */
|
|
131
|
-
isSuperadmin?: (actor: Actor) => boolean;
|
|
132
|
-
};
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* A reference rebac evaluator — one implementation of the injected {@link Authorize} seam,
|
|
136
|
-
* bound to a single `model`. Faithful to `@template/permissions`' `rebac/check` (string-delegate,
|
|
137
|
-
* relation walk with cycle detection, self, json-rules `{ rule }`, any/all, per-row
|
|
138
|
-
* `permissionRules` override) but standalone. Swap it for a richer authorizer in production;
|
|
139
|
-
* this is slated to graduate into `@inixiative/permissions`.
|
|
140
|
-
*/
|
|
141
|
-
declare const makeRebacAuthorize: (options: RebacOptions & {
|
|
142
|
-
model: string;
|
|
143
|
-
}) => Authorize;
|
|
144
|
-
/** Curried form: `createRebac({ schema })(model)` → an {@link Authorize} for that model. */
|
|
145
|
-
declare const createRebac: (options: RebacOptions) => (model: string) => Authorize;
|
|
146
|
-
|
|
147
133
|
/**
|
|
148
134
|
* Authoritative check: the FIRST path whose `from` matches the current record, whose `to` matches
|
|
149
135
|
* the merged record, and whose permissions all pass, wins → `true`. If none pass, returns a
|
|
150
136
|
* {@link Reason} with one {@link PathReason} per candidate path tried.
|
|
137
|
+
*
|
|
138
|
+
* `resource` is the (map-qualified) key into the map — e.g. `db:Inquiry`. Cross-source `permission`
|
|
139
|
+
* checks are handled by the injected {@link Authorize} (wire it to a bridge-aware rebac check, bound
|
|
140
|
+
* to this resource); a `predicate` that reads a bridged relation expects a stitched record.
|
|
151
141
|
*/
|
|
152
|
-
declare const checkTransition: (rules: TransitionMap,
|
|
142
|
+
declare const checkTransition: (rules: TransitionMap, resource: string, action: string, record: Row, changes?: Row, options?: AuthorizeOptions) => CheckResult;
|
|
153
143
|
/**
|
|
154
144
|
* Affordance hint: which actions are offerable from `record` right now. Evaluates ONLY the `from`
|
|
155
145
|
* side (predicate + `from` permission against the current record) — `to` needs the merged record,
|
|
156
146
|
* which doesn't exist without proposed changes, so it defers to {@link checkTransition}.
|
|
157
147
|
*/
|
|
158
|
-
declare const available: (rules: TransitionMap,
|
|
148
|
+
declare const available: (rules: TransitionMap, resource: string, record: Row, options?: AuthorizeOptions) => string[];
|
|
159
149
|
/**
|
|
160
150
|
* Set query: one OR'd Prisma `where` matching every record currently eligible for `action`
|
|
161
151
|
* (the union of all its paths' `from` predicates). Empty action → match-nothing.
|
|
162
152
|
*/
|
|
163
|
-
declare const eligible: (rules: TransitionMap,
|
|
153
|
+
declare const eligible: (rules: TransitionMap, resource: string, action: string) => Row;
|
|
164
154
|
|
|
165
155
|
/**
|
|
166
156
|
* Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?
|
|
@@ -186,9 +176,11 @@ type ValidateOptions = {
|
|
|
186
176
|
};
|
|
187
177
|
/**
|
|
188
178
|
* Authoring validation for a single transition — run on save before persisting a tenant config.
|
|
189
|
-
*
|
|
190
|
-
* `lens` is supplied for
|
|
179
|
+
* Returns structured issues (never throws) on malformed input: predicate validity delegates to
|
|
180
|
+
* json-rules (`validateRule`, plus `checkRuleAgainstLens` when a `lens` is supplied for
|
|
181
|
+
* field/relation scoping); permission shape delegates to `@inixiative/permissions`' `actionRuleSchema`;
|
|
182
|
+
* merge strategy is checked here.
|
|
191
183
|
*/
|
|
192
184
|
declare const validateTransition: (transition: Transition, options?: ValidateOptions) => ValidationResult;
|
|
193
185
|
|
|
194
|
-
export { type Action, type
|
|
186
|
+
export { type Action, type Actor, type Authorize, type AuthorizeOptions, type CheckResult, type Include, type Merge, type MergeStrategy, type PathReason, type PermissionsAuthorizeOptions, type Reason, type Row, type Side, type SideReason, type ToSide, type Transition, type TransitionMap, type ValidateOptions, type ValidationIssue, type ValidationResult, applyMerge, available, checkPath, checkTransition, createAuthorize, describe, eligible, isSerializable, isSerializableMerge, validateTransition };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,30 +1,16 @@
|
|
|
1
|
+
import { ActionRule, RebacSchema, ResolveRelation, Subject } from '@inixiative/permissions';
|
|
2
|
+
export { ActionRule } from '@inixiative/permissions';
|
|
1
3
|
import { Condition, Lens, LensNarrowing } from '@inixiative/json-rules';
|
|
2
4
|
|
|
3
5
|
type Row = Record<string, unknown>;
|
|
4
|
-
|
|
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.
|
|
9
|
-
*/
|
|
10
|
-
type ActionRule = string | {
|
|
11
|
-
rel: string;
|
|
12
|
-
action: string;
|
|
13
|
-
} | {
|
|
14
|
-
self: string;
|
|
15
|
-
} | {
|
|
16
|
-
rule: Condition;
|
|
17
|
-
} | {
|
|
18
|
-
any: ActionRule[];
|
|
19
|
-
} | {
|
|
20
|
-
all: ActionRule[];
|
|
21
|
-
} | null;
|
|
6
|
+
|
|
22
7
|
type Actor = ({
|
|
23
8
|
id?: string | null;
|
|
24
9
|
} & Row) | null | undefined;
|
|
25
10
|
/**
|
|
26
|
-
* Injected permission evaluator.
|
|
27
|
-
* so the consumer closes over whatever its rebac needs (see {@link
|
|
11
|
+
* Injected permission evaluator. Resource-free: the kernel knows nothing about resources or schemas,
|
|
12
|
+
* so the consumer closes over whatever its rebac needs (see {@link createAuthorize}, the adapter
|
|
13
|
+
* over `@inixiative/permissions`).
|
|
28
14
|
*/
|
|
29
15
|
type Authorize = (rule: ActionRule, record: Row, actor: Actor) => boolean;
|
|
30
16
|
/** Serializable merge keywords (Mongo-flavored). Array strategies are field-scoped. */
|
|
@@ -66,7 +52,9 @@ type Action<R extends Row = Row> = {
|
|
|
66
52
|
paths: Transition<R>[];
|
|
67
53
|
label?: string;
|
|
68
54
|
};
|
|
69
|
-
/** `
|
|
55
|
+
/** `resource → action → Action`, where `resource` is the (map-qualified) key — e.g. `db:Inquiry`,
|
|
56
|
+
* matching `@inixiative/permissions`' rebac schema keys so a transition's `permission` resolves
|
|
57
|
+
* against the same resource identity. */
|
|
70
58
|
type TransitionMap = Record<string, Record<string, Action>>;
|
|
71
59
|
/** Why one side failed. Both keys are independent; either, both, or neither may be set. */
|
|
72
60
|
type SideReason = {
|
|
@@ -90,6 +78,34 @@ type AuthorizeOptions = {
|
|
|
90
78
|
authorize?: Authorize;
|
|
91
79
|
};
|
|
92
80
|
|
|
81
|
+
type PermissionsAuthorizeOptions<R extends string = string> = {
|
|
82
|
+
/** The permissions rebac schema: `{ bridges?, permissions }`. */
|
|
83
|
+
schema: RebacSchema<R>;
|
|
84
|
+
/**
|
|
85
|
+
* Resolve a hydrated relation field to the resource it points at (the ORM-specific seam).
|
|
86
|
+
* Default: the relation segment name doubles as the resource key. Cross-map bridges are resolved
|
|
87
|
+
* by the engine from `schema.bridges`, not here.
|
|
88
|
+
*/
|
|
89
|
+
resolveRelation?: ResolveRelation<R>;
|
|
90
|
+
/** Superadmin bypass, derived from the actor; checked before any rule. */
|
|
91
|
+
isSuperadmin?: (actor: Actor) => boolean;
|
|
92
|
+
/**
|
|
93
|
+
* Supplemental hydrated rows (`map:model → rows`) for bridge (cross-map) `rel` walks, derived from
|
|
94
|
+
* the record + actor — the same shape `Subject.data` takes. Only consulted when a walk crosses a
|
|
95
|
+
* bridge and a downstream action reads the far record's fields.
|
|
96
|
+
*/
|
|
97
|
+
data?: (record: Row, actor: Actor) => Subject<R>['data'];
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Bridge `@inixiative/permissions`' rebac `check` onto transitions' {@link Authorize} seam — the
|
|
101
|
+
* production evaluator, injected, not reimplemented. `createAuthorize(options)(resource)` returns an
|
|
102
|
+
* `Authorize` bound to a (map-qualified) `resource`; each call evaluates a per-side `permission`
|
|
103
|
+
* rule against a concrete record + actor. permissions owns the evaluation (string delegation with
|
|
104
|
+
* cycle detection, intra-map `rel` walks via `resolveRelation`, cross-map bridge walks, `{ self }`,
|
|
105
|
+
* abac `{ rule }`, boolean terminals, `any`/`all`, per-row `permissionRules` overrides).
|
|
106
|
+
*/
|
|
107
|
+
declare const createAuthorize: <R extends string = string>(options: PermissionsAuthorizeOptions<R>) => ((resource: R) => Authorize);
|
|
108
|
+
|
|
93
109
|
/**
|
|
94
110
|
* The kernel: evaluate one atomic edge. Reports every failure rather than short-circuiting —
|
|
95
111
|
* `from`/`to` and predicate/permission are independent slots — so a caller sees the whole
|
|
@@ -114,53 +130,27 @@ declare const isSerializableMerge: (merge?: Merge) => boolean;
|
|
|
114
130
|
*/
|
|
115
131
|
declare const applyMerge: <R extends Row>(merge: Merge<R> | undefined, record: R, changes?: Partial<R>) => R;
|
|
116
132
|
|
|
117
|
-
type ModelPermission = {
|
|
118
|
-
actions: Record<string, ActionRule>;
|
|
119
|
-
};
|
|
120
|
-
/** `model → { actions: { actionName → ActionRule } }`. Mirrors `@template/permissions` RebacSchema. */
|
|
121
|
-
type RebacSchema = Record<string, ModelPermission>;
|
|
122
|
-
type RebacOptions = {
|
|
123
|
-
schema: RebacSchema;
|
|
124
|
-
/**
|
|
125
|
-
* Resolve the model a relation points at, given the source model + relation segment.
|
|
126
|
-
* Default: the relation segment name doubles as the target model key. Supply this when your
|
|
127
|
-
* relation field names differ from your model names (the template binds this via prismaMap).
|
|
128
|
-
*/
|
|
129
|
-
resolveModel?: (model: string, relationSegment: string) => string;
|
|
130
|
-
/** Optional superadmin bypass, checked before any rule. */
|
|
131
|
-
isSuperadmin?: (actor: Actor) => boolean;
|
|
132
|
-
};
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* A reference rebac evaluator — one implementation of the injected {@link Authorize} seam,
|
|
136
|
-
* bound to a single `model`. Faithful to `@template/permissions`' `rebac/check` (string-delegate,
|
|
137
|
-
* relation walk with cycle detection, self, json-rules `{ rule }`, any/all, per-row
|
|
138
|
-
* `permissionRules` override) but standalone. Swap it for a richer authorizer in production;
|
|
139
|
-
* this is slated to graduate into `@inixiative/permissions`.
|
|
140
|
-
*/
|
|
141
|
-
declare const makeRebacAuthorize: (options: RebacOptions & {
|
|
142
|
-
model: string;
|
|
143
|
-
}) => Authorize;
|
|
144
|
-
/** Curried form: `createRebac({ schema })(model)` → an {@link Authorize} for that model. */
|
|
145
|
-
declare const createRebac: (options: RebacOptions) => (model: string) => Authorize;
|
|
146
|
-
|
|
147
133
|
/**
|
|
148
134
|
* Authoritative check: the FIRST path whose `from` matches the current record, whose `to` matches
|
|
149
135
|
* the merged record, and whose permissions all pass, wins → `true`. If none pass, returns a
|
|
150
136
|
* {@link Reason} with one {@link PathReason} per candidate path tried.
|
|
137
|
+
*
|
|
138
|
+
* `resource` is the (map-qualified) key into the map — e.g. `db:Inquiry`. Cross-source `permission`
|
|
139
|
+
* checks are handled by the injected {@link Authorize} (wire it to a bridge-aware rebac check, bound
|
|
140
|
+
* to this resource); a `predicate` that reads a bridged relation expects a stitched record.
|
|
151
141
|
*/
|
|
152
|
-
declare const checkTransition: (rules: TransitionMap,
|
|
142
|
+
declare const checkTransition: (rules: TransitionMap, resource: string, action: string, record: Row, changes?: Row, options?: AuthorizeOptions) => CheckResult;
|
|
153
143
|
/**
|
|
154
144
|
* Affordance hint: which actions are offerable from `record` right now. Evaluates ONLY the `from`
|
|
155
145
|
* side (predicate + `from` permission against the current record) — `to` needs the merged record,
|
|
156
146
|
* which doesn't exist without proposed changes, so it defers to {@link checkTransition}.
|
|
157
147
|
*/
|
|
158
|
-
declare const available: (rules: TransitionMap,
|
|
148
|
+
declare const available: (rules: TransitionMap, resource: string, record: Row, options?: AuthorizeOptions) => string[];
|
|
159
149
|
/**
|
|
160
150
|
* Set query: one OR'd Prisma `where` matching every record currently eligible for `action`
|
|
161
151
|
* (the union of all its paths' `from` predicates). Empty action → match-nothing.
|
|
162
152
|
*/
|
|
163
|
-
declare const eligible: (rules: TransitionMap,
|
|
153
|
+
declare const eligible: (rules: TransitionMap, resource: string, action: string) => Row;
|
|
164
154
|
|
|
165
155
|
/**
|
|
166
156
|
* Can this transition be persisted (stored in the DB, edited in a UI, sent over the wire)?
|
|
@@ -186,9 +176,11 @@ type ValidateOptions = {
|
|
|
186
176
|
};
|
|
187
177
|
/**
|
|
188
178
|
* Authoring validation for a single transition — run on save before persisting a tenant config.
|
|
189
|
-
*
|
|
190
|
-
* `lens` is supplied for
|
|
179
|
+
* Returns structured issues (never throws) on malformed input: predicate validity delegates to
|
|
180
|
+
* json-rules (`validateRule`, plus `checkRuleAgainstLens` when a `lens` is supplied for
|
|
181
|
+
* field/relation scoping); permission shape delegates to `@inixiative/permissions`' `actionRuleSchema`;
|
|
182
|
+
* merge strategy is checked here.
|
|
191
183
|
*/
|
|
192
184
|
declare const validateTransition: (transition: Transition, options?: ValidateOptions) => ValidationResult;
|
|
193
185
|
|
|
194
|
-
export { type Action, type
|
|
186
|
+
export { type Action, type Actor, type Authorize, type AuthorizeOptions, type CheckResult, type Include, type Merge, type MergeStrategy, type PathReason, type PermissionsAuthorizeOptions, type Reason, type Row, type Side, type SideReason, type ToSide, type Transition, type TransitionMap, type ValidateOptions, type ValidationIssue, type ValidationResult, applyMerge, available, checkPath, checkTransition, createAuthorize, describe, eligible, isSerializable, isSerializableMerge, 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
|
|
1
|
+
import {createRebacCheck}from'@inixiative/permissions';import {check,toPrisma,validateRule,checkRuleAgainstLens}from'@inixiative/json-rules';import {mergeWith,cloneDeep,get,set,uniqWith,isEqual}from'lodash-es';import {actionRuleSchema}from'@inixiative/permissions/actionRuleSchema';var z=/Cycle detected/,P=(e,t)=>({check:()=>false,isSuperadmin:()=>t?.(e)??false,getUserId:()=>e?.id??null}),W=e=>{let t=e.resolveRelation??((i,n)=>n),o=createRebacCheck(t);return i=>(n,r,a)=>{let p=P(a,e.isSuperadmin),c={resource:i,record:r,data:e.data?.(r,a)};try{return o(p,e.schema,c,n)}catch(s){if(s instanceof Error&&z.test(s.message))return false;throw s}}};var R=e=>Array.isArray(e)?e:e===void 0?[]:[e],q=(e,t)=>Array.isArray(t)?t:void 0,f=e=>typeof e!="function",h=(e,t,o={})=>{if(typeof e=="function")return e(t,o);let i=e??"spread";if(i==="spread")return {...t,...o};if(i==="deepMerge")return mergeWith(cloneDeep(t),cloneDeep(o),q);let{kind:n,path:r}=i,a=cloneDeep({...t,...o}),p=[...R(get(t,r)),...R(get(o,r))];return set(a,r,n==="appendUnique"?uniqWith(p,isEqual):p),a};var y=e=>typeof e=="string"?e:"predicate not satisfied",A=(e,t,o,i)=>!e||t===void 0?false:!e(t,o,i),w=(e,t,o={},i={})=>{let{actor:n,authorize:r}=i,a=h(e.to.merge,t,o),p={},c=check(e.from.predicate,t);c!==true&&(p.predicate=y(c)),A(r,e.from.permission,t,n)&&(p.permission="not authorized");let s={},m=check(e.to.predicate,a);m!==true&&(s.predicate=y(m)),A(r,e.to.permission,a,n)&&(s.permission="not authorized");let u={};return (p.predicate||p.permission)&&(u.from=p),(s.predicate||s.permission)&&(u.to=s),u.from||u.to?u:true};var b=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"},J=e=>e.paths.length===0?"no transition path available":e.paths.length===1?b(e.paths[0]):e.paths.map((t,o)=>`path ${o}: ${b(t)}`).join(" | ");var k=(e,t,o)=>{let i=e[t]?.[o];if(!i)throw new Error(`transition: no action "${o}" registered on resource "${t}"`);return i},ee=(e,t,o,i,n={},r={})=>{let a=k(e,t,o),p=[];for(let c of a.paths){let s=w(c,i,n,r);if(s===true)return true;p.push(s);}return {paths:p}},te=(e,t,o,i={})=>{let n=e[t];if(!n)return [];let{actor:r,authorize:a}=i,p=(c,s)=>!a||c===void 0||a(c,s,r);return Object.entries(n).filter(([,c])=>c.paths.some(s=>check(s.from.predicate,o)===true&&p(s.from.permission,o))).map(([c])=>c)},oe=(e,t,o)=>{let i=k(e,t,o),{steps:n}=toPrisma({any:i.paths.map(r=>r.from.predicate)});return n[n.length-1].where};var re=e=>f(e.to.merge);var I=new Set(["spread","deepMerge"]),E=new Set(["append","appendUnique"]),N=(e,t,o,i)=>{if(e===void 0){t.push({path:o,message:"predicate is required"});return}let n=validateRule(e);for(let r of n.errors)t.push({path:`${o}.${r.path}`,message:r.message});if(i){let r=checkRuleAgainstLens(e,i);for(let a of r.violations)t.push({path:`${o}.${a.path}`,message:a.reason});}},_=(e,t,o)=>{if(e===void 0)return;let i=actionRuleSchema.safeParse(e);if(!i.success)for(let n of i.error.issues)n.path.length===0?t.push({path:o,message:"unrecognized ActionRule shape"}):t.push({path:`${o}.${n.path.join(".")}`,message:n.message});},D=(e,t,o)=>{if(!(e===void 0||typeof e=="function")){if(typeof e=="string"){I.has(e)||t.push({path:o,message:`unknown merge strategy "${e}"`});return}E.has(e.kind)?e.path||t.push({path:o,message:`merge "${e.kind}" requires a \`path\``}):t.push({path:o,message:`unknown merge kind "${e.kind}"`});}},x=(e,t,o,i)=>{if(e===null||typeof e!="object"){t.push({path:o,message:`\`${o}\` side is required`});return}N(e.predicate,t,`${o}.predicate`,i.lens),_(e.permission,t,`${o}.permission`),e.requires!==void 0&&(typeof e.requires!="object"||e.requires===null)&&t.push({path:`${o}.requires`,message:"`requires` must be a Prisma-include-shaped object"}),"merge"in e&&D(e.merge,t,`${o}.merge`);},ue=(e,t={})=>{let o=[];return x(e?.from,o,"from",t),x(e?.to,o,"to",t),t.requireSerializable&&!f(e?.to?.merge)&&o.push({path:"to.merge",message:"callback merge is not serializable; use a keyword strategy"}),{ok:o.length===0,errors:o}};export{h as applyMerge,te as available,w as checkPath,ee as checkTransition,W as createAuthorize,J as describe,oe as eligible,re as isSerializable,f as isSerializableMerge,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","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","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,CAAQ,GAAGC,CAAQ,CAAA,CAG1D,GAAIC,CAAAA,GAAa,WAAA,CACf,OAAOC,SAAAA,CAAUC,SAAAA,CAAUJ,CAAM,CAAA,CAAGI,UAAUH,CAAO,CAAA,CAAGP,CAAa,CAAA,CAGvE,GAAM,CAAE,IAAA,CAAAW,CAAAA,CAAM,IAAA,CAAAC,CAAK,CAAA,CAAIJ,CAAAA,CACjBK,CAAAA,CAAOH,SAAAA,CAAU,CAAE,GAAGJ,CAAAA,CAAQ,GAAGC,CAAQ,CAAC,CAAA,CAC1CO,CAAAA,CAAS,CAAC,GAAGhB,EAAQiB,GAAAA,CAAIT,CAAAA,CAAQM,CAAI,CAAC,CAAA,CAAG,GAAGd,CAAAA,CAAQiB,GAAAA,CAAIR,EAASK,CAAI,CAAC,CAAC,CAAA,CAC7E,OAAAI,GAAA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,MAAA,CAAQ,EACxE,CAAA,CAOa0E,GAAqB,CAChC5D,CAAAA,CACAC,CAAAA,CAA2B,KACN,CACrB,IAAMgD,CAAAA,CAA4B,GAClC,OAAAS,CAAAA,CAAa1D,CAAAA,CAAW,IAAA,CAAMiD,CAAAA,CAAQ,MAAA,CAAQhD,CAAO,CAAA,CACrDyD,EAAa1D,CAAAA,CAAW,EAAA,CAAIiD,CAAAA,CAAQ,IAAA,CAAMhD,CAAO,CAAA,CAC7CA,CAAAA,CAAQ,mBAAA,EAAuB,CAACxB,EAAoBuB,CAAAA,CAAW,EAAA,CAAG,KAAK,CAAA,EACzEiD,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, model: string, action: string): Action => {\n const found = rules[model]?.[action];\n if (!found) throw new Error(`transition: no action \"${action}\" registered on model \"${model}\"`);\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 */\nexport const checkTransition = (\n rules: TransitionMap,\n model: string,\n action: string,\n record: Row,\n changes: Row = {},\n options: AuthorizeOptions = {},\n): CheckResult => {\n const found = getAction(rules, model, 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 model: string,\n record: Row,\n options: AuthorizeOptions = {},\n): string[] => {\n const actions = rules[model];\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, model: string, action: string): Row => {\n const found = getAction(rules, model, 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"]}
|
|
1
|
+
{"version":3,"sources":["../src/authorize.ts","../src/merge.ts","../src/check.ts","../src/describe.ts","../src/registry.ts","../src/serializable.ts","../src/validate.ts"],"names":["CYCLE","actorPermix","actor","isSuperadmin","createAuthorize","options","resolveRelation","_resource","segment","check","createRebacCheck","resource","rule","record","permix","subject","error","toArray","value","replaceArrays","_target","source","isSerializableMerge","merge","applyMerge","changes","strategy","mergeWith","cloneDeep","kind","path","base","merged","get","set","uniqWith","isEqual","predicateReason","result","denies","authorize","checkPath","transition","next","from","fromPredicate","checkRule","to","toPredicate","reason","describePath","segs","describe","i","getAction","rules","action","found","checkTransition","paths","available","actions","allows","rec","eligible","steps","toPrisma","isSerializable","MERGE_KEYWORDS","ARRAY_KINDS","validatePredicate","predicate","errors","lens","validateRule","issue","lensCheck","checkRuleAgainstLens","violation","validatePermission","parsed","actionRuleSchema","validateMerge","validateSide","side","validateTransition"],"mappings":"0RAYA,IAAMA,CAAAA,CAAQ,gBAAA,CAwBRC,CAAAA,CAAc,CAACC,CAAAA,CAAcC,CAAAA,IAA0D,CAC3F,KAAA,CAAO,IAAM,KAAA,CACb,YAAA,CAAc,IAAMA,CAAAA,GAAeD,CAAK,CAAA,EAAK,KAAA,CAC7C,SAAA,CAAW,IAAMA,CAAAA,EAAO,EAAA,EAAM,IAChC,CAAA,CAAA,CAUaE,CAAAA,CACXC,CAAAA,EACiC,CACjC,IAAMC,CAAAA,CACJD,CAAAA,CAAQ,eAAA,GAAoB,CAACE,CAAAA,CAAWC,CAAAA,GAAYA,CAAAA,CAAAA,CAChDC,CAAAA,CAAQC,gBAAAA,CAAoBJ,CAAe,CAAA,CAEjD,OAAQK,CAAAA,EACN,CAACC,CAAAA,CAAMC,CAAAA,CAAQX,CAAAA,GAAU,CACvB,IAAMY,CAAAA,CAASb,CAAAA,CAAYC,CAAAA,C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c,OAAOA,CAAAA,CAAK,QAAA,EAAa,QAAA,EAAYA,CAAAA,CAAK,QAAA,GAAa,IAAA,CAAA,EACzFZ,CAAAA,CAAO,IAAA,CAAK,CACV,IAAA,CAAM,CAAA,EAAG1C,CAAI,YACb,OAAA,CAAS,mDACX,CAAC,CAAA,CACC,OAAA,GAAWsD,CAAAA,EAAMF,CAAAA,CAAcE,CAAAA,CAAK,KAAA,CAAOZ,CAAAA,CAAQ,CAAA,EAAG1C,CAAI,CAAA,MAAA,CAAQ,EACxE,CAAA,CASauD,EAAAA,CAAqB,CAChC3C,CAAAA,CACArC,CAAAA,CAA2B,EAAC,GACP,CACrB,IAAMmE,CAAAA,CAA4B,EAAC,CACnC,OAAAW,CAAAA,CAAazC,CAAAA,EAAY,IAAA,CAAM8B,CAAAA,CAAQ,MAAA,CAAQnE,CAAO,CAAA,CACtD8E,CAAAA,CAAazC,CAAAA,EAAY,EAAA,CAAI8B,CAAAA,CAAQ,IAAA,CAAMnE,CAAO,CAAA,CAC9CA,CAAAA,CAAQ,mBAAA,EAAuB,CAACiB,CAAAA,CAAoBoB,CAAAA,EAAY,EAAA,EAAI,KAAK,CAAA,EAC3E8B,CAAAA,CAAO,IAAA,CAAK,CACV,IAAA,CAAM,UAAA,CACN,OAAA,CAAS,4DACX,CAAC,CAAA,CACI,CAAE,EAAA,CAAIA,CAAAA,CAAO,MAAA,GAAW,CAAA,CAAG,MAAA,CAAAA,CAAO,CAC3C","file":"index.js","sourcesContent":["import {\n type ActionRule,\n createRebacCheck,\n type PermixLike,\n type RebacSchema,\n type ResolveRelation,\n type Subject,\n} from '@inixiative/permissions';\nimport type { Actor, Authorize, Row } from './types';\n\n// permissions surfaces a cyclic permission graph by throwing; the transitions guard denies (fail\n// closed) so a misconfigured schema terminates cleanly instead of propagating out of the kernel.\nconst CYCLE = /Cycle detected/;\n\nexport type PermissionsAuthorizeOptions<R extends string = string> = {\n /** The permissions rebac schema: `{ bridges?, permissions }`. */\n schema: RebacSchema<R>;\n /**\n * Resolve a hydrated relation field to the resource it points at (the ORM-specific seam).\n * Default: the relation segment name doubles as the resource key. Cross-map bridges are resolved\n * by the engine from `schema.bridges`, not here.\n */\n resolveRelation?: ResolveRelation<R>;\n /** Superadmin bypass, derived from the actor; checked before any rule. */\n isSuperadmin?: (actor: Actor) => boolean;\n /**\n * Supplemental hydrated rows (`map:model → rows`) for bridge (cross-map) `rel` walks, derived from\n * the record + actor — the same shape `Subject.data` takes. Only consulted when a walk crosses a\n * bridge and a downstream action reads the far record's fields.\n */\n data?: (record: Row, actor: Actor) => Subject<R>['data'];\n};\n\n// The transitions seam carries no pre-granted (role-derived) permix state, so a direct permix grant\n// always misses and authorization is decided entirely by the schema. The actor supplies only its id\n// (for `{ self }`) and an optional superadmin bypass.\nconst actorPermix = (actor: Actor, isSuperadmin?: (actor: Actor) => boolean): PermixLike => ({\n check: () => false,\n isSuperadmin: () => isSuperadmin?.(actor) ?? false,\n getUserId: () => actor?.id ?? null,\n});\n\n/**\n * Bridge `@inixiative/permissions`' rebac `check` onto transitions' {@link Authorize} seam — the\n * production evaluator, injected, not reimplemented. `createAuthorize(options)(resource)` returns an\n * `Authorize` bound to a (map-qualified) `resource`; each call evaluates a per-side `permission`\n * rule against a concrete record + actor. permissions owns the evaluation (string delegation with\n * cycle detection, intra-map `rel` walks via `resolveRelation`, cross-map bridge walks, `{ self }`,\n * abac `{ rule }`, boolean terminals, `any`/`all`, per-row `permissionRules` overrides).\n */\nexport const createAuthorize = <R extends string = string>(\n options: PermissionsAuthorizeOptions<R>,\n): ((resource: R) => Authorize) => {\n const resolveRelation: ResolveRelation<R> =\n options.resolveRelation ?? ((_resource, segment) => segment as R);\n const check = createRebacCheck<R>(resolveRelation);\n\n return (resource: R): Authorize =>\n (rule, record, actor) => {\n const permix = actorPermix(actor, options.isSuperadmin);\n const subject: Subject<R> = { resource, record, data: options.data?.(record, actor) };\n try {\n return check(permix, options.schema, subject, rule as ActionRule);\n } catch (error) {\n if (error instanceof Error && CYCLE.test(error.message)) return false;\n throw error;\n }\n };\n};\n","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, 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 // toPrisma always terminates a plan in a WhereStep (and throws on count-based ops,\n // which would need a multi-step plan, since we pass no map/model). Trust that contract.\n const { steps } = toPrisma({ any: found.paths.map((path) => path.from.predicate) });\n return (steps[steps.length - 1] as { where: Row }).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 { actionRuleSchema } from '@inixiative/permissions/actionRuleSchema';\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 | undefined,\n errors: ValidationIssue[],\n path: string,\n lens?: Lens | LensNarrowing,\n): void => {\n if (predicate === undefined) {\n errors.push({ path, message: 'predicate is required' });\n return;\n }\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\n// Validate the whole ActionRule against `@inixiative/permissions`' zod schema — the single source of\n// truth for the algebra (boolean terminals, string delegation, `{ rel, action }`, `{ self }`, abac\n// `{ rule }`, `any`/`all`, `null`). A malformed rule yields a structured issue rather than throwing.\nconst validatePermission = (\n rule: ActionRule | undefined,\n errors: ValidationIssue[],\n path: string,\n): void => {\n if (rule === undefined) return; // absent = open\n const parsed = actionRuleSchema.safeParse(rule);\n if (parsed.success) return;\n for (const issue of parsed.error.issues) {\n // A root union failure (zod reports an empty relative path) means none of the ActionRule shapes\n // matched; nested issues keep their zod path + message.\n if (issue.path.length === 0) {\n errors.push({ path, message: 'unrecognized ActionRule shape' });\n } else {\n errors.push({ path: `${path}.${issue.path.join('.')}`, message: issue.message });\n }\n }\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 | undefined,\n errors: ValidationIssue[],\n path: string,\n options: ValidateOptions,\n): void => {\n if (side === null || typeof side !== 'object') {\n errors.push({ path, message: `\\`${path}\\` side is required` });\n return;\n }\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 * Returns structured issues (never throws) on malformed input: predicate validity delegates to\n * json-rules (`validateRule`, plus `checkRuleAgainstLens` when a `lens` is supplied for\n * field/relation scoping); permission shape delegates to `@inixiative/permissions`' `actionRuleSchema`;\n * merge strategy is 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
|
|
3
|
+
"version": "0.1.0",
|
|
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",
|
|
@@ -17,9 +17,9 @@
|
|
|
17
17
|
"typecheck": "tsc --noEmit",
|
|
18
18
|
"lint": "biome check .",
|
|
19
19
|
"format": "biome format --write .",
|
|
20
|
-
"check": "bun run typecheck && bun run lint",
|
|
20
|
+
"check": "bun run typecheck && bun run lint && bun run test",
|
|
21
21
|
"prepare": "lefthook install",
|
|
22
|
-
"prepublishOnly": "bun run check && bun run
|
|
22
|
+
"prepublishOnly": "bun run check && bun run build"
|
|
23
23
|
},
|
|
24
24
|
"keywords": [
|
|
25
25
|
"transition",
|
|
@@ -40,12 +40,13 @@
|
|
|
40
40
|
"access": "public"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
|
-
"@biomejs/biome": "
|
|
44
|
-
"@types/bun": "
|
|
43
|
+
"@biomejs/biome": "2.5.2",
|
|
44
|
+
"@types/bun": "1.3.14",
|
|
45
45
|
"@types/lodash-es": "^4.17.12",
|
|
46
|
-
"lefthook": "
|
|
47
|
-
"tsup": "
|
|
48
|
-
"typescript": "
|
|
46
|
+
"lefthook": "2.1.9",
|
|
47
|
+
"tsup": "8.5.1",
|
|
48
|
+
"typescript": "6.0.3",
|
|
49
|
+
"@inixiative/config": "^0.2.1"
|
|
49
50
|
},
|
|
50
51
|
"peerDependencies": {
|
|
51
52
|
"typescript": "^5.0.0"
|
|
@@ -56,8 +57,10 @@
|
|
|
56
57
|
}
|
|
57
58
|
},
|
|
58
59
|
"dependencies": {
|
|
59
|
-
"@inixiative/json-rules": "^2.
|
|
60
|
-
"
|
|
60
|
+
"@inixiative/json-rules": "^2.13.0",
|
|
61
|
+
"@inixiative/permissions": "^0.3.1",
|
|
62
|
+
"lodash-es": "^4.18.1",
|
|
63
|
+
"zod": "^4.4.3"
|
|
61
64
|
},
|
|
62
65
|
"exports": {
|
|
63
66
|
".": {
|
|
@@ -65,5 +68,6 @@
|
|
|
65
68
|
"import": "./dist/index.js",
|
|
66
69
|
"require": "./dist/index.cjs"
|
|
67
70
|
}
|
|
68
|
-
}
|
|
71
|
+
},
|
|
72
|
+
"packageManager": "bun@1.3.14"
|
|
69
73
|
}
|