@geonosis/policy 3.0.0 → 3.2.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/CHANGELOG.md +13 -0
- package/dist/conformance.d.cts +1 -12
- package/dist/conformance.d.ts +1 -12
- package/dist/define.d.cts +2 -22
- package/dist/define.d.ts +2 -22
- package/dist/drizzle/index.cjs +2 -17
- package/dist/drizzle/index.d.cts +3 -11
- package/dist/drizzle/index.d.ts +3 -11
- package/dist/drizzle/index.js +2 -17
- package/dist/journal-events.d.cts +1 -14
- package/dist/journal-events.d.ts +1 -14
- package/dist/lattice.cjs +11 -3
- package/dist/lattice.d.cts +4 -37
- package/dist/lattice.d.ts +4 -37
- package/dist/lattice.js +11 -3
- package/dist/learning.cjs +10 -4
- package/dist/learning.d.cts +5 -58
- package/dist/learning.d.ts +5 -58
- package/dist/learning.js +10 -4
- package/dist/markdown.d.cts +2 -19
- package/dist/markdown.d.ts +2 -19
- package/dist/medusa/index.cjs +3 -18
- package/dist/medusa/index.d.cts +5 -46
- package/dist/medusa/index.d.ts +5 -46
- package/dist/medusa/index.js +2 -17
- package/dist/permissions/index.cjs +8 -4
- package/dist/permissions/index.d.cts +8 -67
- package/dist/permissions/index.d.ts +8 -67
- package/dist/permissions/index.js +8 -4
- package/dist/read.cjs +5 -11
- package/dist/read.d.cts +2 -31
- package/dist/read.d.ts +2 -31
- package/dist/read.js +1 -7
- package/dist/rows.cjs +17 -0
- package/dist/rows.d.cts +6 -9
- package/dist/rows.d.ts +6 -9
- package/dist/rows.js +17 -0
- package/dist/seed.d.cts +1 -13
- package/dist/seed.d.ts +1 -13
- package/dist/threshold.cjs +5 -1
- package/dist/threshold.d.cts +3 -29
- package/dist/threshold.d.ts +3 -29
- package/dist/threshold.js +5 -1
- package/dist/types.d.cts +2 -57
- package/dist/types.d.ts +2 -57
- package/package.json +1 -1
package/dist/learning.d.ts
CHANGED
|
@@ -1,39 +1,9 @@
|
|
|
1
1
|
import type { JournalObservationEntry, Policy, PolicyRule, PolicyScope } from './types.js';
|
|
2
|
-
/**
|
|
3
|
-
|
|
4
|
-
* reversibly.
|
|
5
|
-
*
|
|
6
|
-
* Shaped after ACE (Generator / Reflector / Curator): the playbook EVOLVES by increments rather
|
|
7
|
-
* than rewrites, which is what stops accumulated context from collapsing as it grows.
|
|
8
|
-
*
|
|
9
|
-
* observeJournal deterministic signal extraction — no model, fully testable. The strongest
|
|
10
|
-
* signals are BEHAVIOURAL: a human reversing an automated decision is unambiguous
|
|
11
|
-
* feedback in a way a survey never is.
|
|
12
|
-
* reflect folds repeats into one candidate each. An agent may propose candidates too;
|
|
13
|
-
* they enter through this same gate.
|
|
14
|
-
* curate merges by stable id, ACCUMULATING evidence instead of overwriting statements.
|
|
15
|
-
* promote evidence-gated. demote is always available and always recorded — auditable
|
|
16
|
-
* unlearning is the point.
|
|
17
|
-
*
|
|
18
|
-
* The safety rail is the lattice: an active learning becomes a rule at the ADVISORY tier, which
|
|
19
|
-
* can only ever fill silence. The loop can suggest; it can never quietly change what a business does.
|
|
20
|
-
*/
|
|
21
|
-
export type LearningKind =
|
|
22
|
-
/** A working practice worth repeating. */
|
|
23
|
-
'heuristic'
|
|
24
|
-
/** A trap worth naming, so the next session starts knowing it. */
|
|
25
|
-
| 'pitfall'
|
|
26
|
-
/** Policy and the people running the business disagree, repeatedly. */
|
|
27
|
-
| 'rule-friction'
|
|
28
|
-
/** The same sequence keeps being run by hand — name it. */
|
|
29
|
-
| 'macro'
|
|
30
|
-
/** A knob that exists but nothing sets, so a hardcoded default rules instead. */
|
|
31
|
-
| 'unset-policy';
|
|
2
|
+
/** ACE-shaped (Generator / Reflector / Curator): the playbook evolves by increments, not rewrites. `observeJournal` extracts deterministic signals, `reflect` folds repeats into candidates, curation merges them, and demotion is always available and recorded. */
|
|
3
|
+
export type LearningKind = 'heuristic' | 'pitfall' | 'rule-friction' | 'macro' | 'unset-policy';
|
|
32
4
|
export type LearningStatus = 'active' | 'candidate' | 'demoted';
|
|
33
5
|
export type LearningEvidence = {
|
|
34
|
-
/** Ids of the journal entries that support it. */
|
|
35
6
|
journalRefs: string[];
|
|
36
|
-
/** Measured effect, when there is one. */
|
|
37
7
|
metric?: {
|
|
38
8
|
delta: number;
|
|
39
9
|
name: string;
|
|
@@ -44,14 +14,12 @@ export type LearningEvidence = {
|
|
|
44
14
|
export type Learning = {
|
|
45
15
|
demotedReason?: string;
|
|
46
16
|
evidence: LearningEvidence;
|
|
47
|
-
/**
|
|
17
|
+
/** Curation merges on this key, so evidence accumulates. */
|
|
48
18
|
id: string;
|
|
49
19
|
kind: LearningKind;
|
|
50
20
|
scope?: PolicyScope;
|
|
51
|
-
/** What was learned, in words a human can audit and edit. */
|
|
52
21
|
statement: string;
|
|
53
22
|
status: LearningStatus;
|
|
54
|
-
/** The advisory constraint this implies, if any. */
|
|
55
23
|
suggests?: {
|
|
56
24
|
kind: string;
|
|
57
25
|
value: unknown;
|
|
@@ -73,32 +41,19 @@ export type Observation = {
|
|
|
73
41
|
};
|
|
74
42
|
};
|
|
75
43
|
export declare const emptyPlaybook: () => Playbook;
|
|
76
|
-
/** Repeated evidence, not one lucky quarter. */
|
|
77
44
|
export declare const DEFAULT_MIN_OBSERVATIONS = 3;
|
|
78
45
|
export declare class LearningError extends Error {
|
|
79
46
|
readonly code: 'INSUFFICIENT_EVIDENCE' | 'UNKNOWN_LEARNING';
|
|
80
47
|
constructor(code: 'INSUFFICIENT_EVIDENCE' | 'UNKNOWN_LEARNING', message: string);
|
|
81
48
|
}
|
|
82
49
|
export type ObserveOptions = {
|
|
83
|
-
/** How few repeats of one operation are still a one-off. */
|
|
84
50
|
minRepeatsForMacro?: number;
|
|
85
|
-
/** The prefix a refusal carries, so friction is countable per rule. That word is a repo's own. */
|
|
86
51
|
refusalPrefix?: string;
|
|
87
|
-
/** What a human doing the undoing tends to call it. */
|
|
88
52
|
reversalVerbs?: RegExp;
|
|
89
53
|
};
|
|
90
|
-
/**
|
|
91
|
-
* The deterministic signals in a journal. Only behaviour that actually happened counts; nothing is
|
|
92
|
-
* inferred from intent alone.
|
|
93
|
-
*/
|
|
94
54
|
export declare const observeJournal: (entries: readonly JournalObservationEntry[], options?: ObserveOptions) => Observation[];
|
|
95
|
-
/** Fold repeats into one candidate each — the statistical reflector. */
|
|
96
55
|
export declare const reflect: (observations: readonly Observation[], now?: Date) => Learning[];
|
|
97
|
-
/**
|
|
98
|
-
* Merge candidates into the playbook. Evidence ACCUMULATES, and a statement is only refreshed while
|
|
99
|
-
* the entry is still under review — an active learning's wording is stable, which is what makes the
|
|
100
|
-
* playbook readable a year later.
|
|
101
|
-
*/
|
|
56
|
+
/** Evidence accumulates; wording is refreshed only while an entry is under review, so an active learning stays stable. */
|
|
102
57
|
export declare const curate: (playbook: Playbook, candidates: readonly Learning[]) => Playbook;
|
|
103
58
|
export declare const promote: (playbook: Playbook, id: string, options?: {
|
|
104
59
|
metric?: {
|
|
@@ -107,15 +62,7 @@ export declare const promote: (playbook: Playbook, id: string, options?: {
|
|
|
107
62
|
};
|
|
108
63
|
minObservations?: number;
|
|
109
64
|
}) => Playbook;
|
|
110
|
-
/** Demotion is always available and always recorded — auditable unlearning. */
|
|
111
65
|
export declare const demote: (playbook: Playbook, id: string, reason: string) => Playbook;
|
|
112
|
-
/**
|
|
113
|
-
* Active learnings that imply a constraint, as rules at the tier the policy calls advisory.
|
|
114
|
-
*
|
|
115
|
-
* A Medusa storefront writes `tier: 'learned'` into this function. Here the tier is read off the
|
|
116
|
-
* lattice, because a policy that declares none has nowhere safe to put a suggestion — and quietly
|
|
117
|
-
* choosing one would hand a suggestion the authority of an SOP.
|
|
118
|
-
*/
|
|
66
|
+
/** The tier is read off the lattice's advisory tier: guessing one would hand a suggestion the authority of an SOP. */
|
|
119
67
|
export declare const playbookRules: (policy: Policy, playbook: Playbook) => PolicyRule[];
|
|
120
|
-
/** The playbook as agent-readable guidance — a delta on top of a built prompt, never a replacement. */
|
|
121
68
|
export declare const playbookGuidance: (playbook: Playbook) => string;
|
package/dist/learning.js
CHANGED
|
@@ -34,10 +34,11 @@ var observeReversals = (entries, verbs) => {
|
|
|
34
34
|
}
|
|
35
35
|
return out;
|
|
36
36
|
};
|
|
37
|
+
var escaped = (literal) => literal.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
|
|
37
38
|
var observeRuleFriction = (entry, prefix) => {
|
|
38
39
|
if (!entry.error)
|
|
39
40
|
return [];
|
|
40
|
-
const [, ruleId, detail] = new RegExp(`${prefix}: ([\\w:.-]+)(?: — (.*))?`).exec(entry.error) ?? [];
|
|
41
|
+
const [, ruleId, detail] = new RegExp(`${escaped(prefix)}: ([\\w:.-]+)(?: — (.*))?`).exec(entry.error) ?? [];
|
|
41
42
|
if (!ruleId)
|
|
42
43
|
return [];
|
|
43
44
|
return [
|
|
@@ -80,8 +81,9 @@ var observeRecurringOps = (entries, minimum) => {
|
|
|
80
81
|
statement: `"${op}" ran ${refs.length} times — save it as a named strategy`
|
|
81
82
|
}));
|
|
82
83
|
};
|
|
84
|
+
var unsticky = (verbs) => new RegExp(verbs.source, verbs.flags.replaceAll(/[gy]/g, ""));
|
|
83
85
|
var observeJournal = (entries, options = {}) => [
|
|
84
|
-
...observeReversals(entries, options.reversalVerbs ?? DEFAULT_REVERSAL_VERBS),
|
|
86
|
+
...observeReversals(entries, unsticky(options.reversalVerbs ?? DEFAULT_REVERSAL_VERBS)),
|
|
85
87
|
...entries.flatMap((entry) => [
|
|
86
88
|
...observeRuleFriction(entry, options.refusalPrefix ?? DEFAULT_REFUSAL_PREFIX),
|
|
87
89
|
...observeUnsetPolicy(entry)
|
|
@@ -118,8 +120,12 @@ var curate = (playbook, candidates) => {
|
|
|
118
120
|
for (const candidate of candidates) {
|
|
119
121
|
const existing = byId.get(candidate.id);
|
|
120
122
|
if (!existing) {
|
|
121
|
-
|
|
122
|
-
|
|
123
|
+
const copy = {
|
|
124
|
+
...candidate,
|
|
125
|
+
evidence: { ...candidate.evidence, journalRefs: [...candidate.evidence.journalRefs] }
|
|
126
|
+
};
|
|
127
|
+
entries.push(copy);
|
|
128
|
+
byId.set(copy.id, copy);
|
|
123
129
|
continue;
|
|
124
130
|
}
|
|
125
131
|
if (existing.status === "demoted")
|
package/dist/markdown.d.cts
CHANGED
|
@@ -1,35 +1,18 @@
|
|
|
1
1
|
import type { Playbook } from './learning.cjs';
|
|
2
2
|
import type { Policy, PolicyRule } from './types.cjs';
|
|
3
|
-
/**
|
|
4
|
-
* The policy as prose, generated beside the data it renders.
|
|
5
|
-
*
|
|
6
|
-
* musa checks in `policy/policy.json` and a `POLICY.md` written from it on every change, and the
|
|
7
|
-
* argument for generating rather than writing it is in that file's own history: two of its sections
|
|
8
|
-
* were prose, and both had gone stale and were telling agents the opposite of what the code did. A
|
|
9
|
-
* markdown that has to be remembered separately drifts, and a drifted one is worse than none — it
|
|
10
|
-
* reads authoritative while the engine enforces something else.
|
|
11
|
-
*
|
|
12
|
-
* So every count, every precedence sentence and every honesty report below is DERIVED.
|
|
13
|
-
*/
|
|
3
|
+
/** Generated beside the data it renders: hand-written sections went stale and told agents the opposite of what the engine enforced. Every count, precedence sentence and honesty report is derived. */
|
|
14
4
|
export type PolicyMarkdownOptions = {
|
|
15
5
|
generator?: string;
|
|
16
6
|
playbook?: Playbook;
|
|
17
7
|
rules?: readonly PolicyRule[];
|
|
18
|
-
/** What a reader should edit instead of this file. */
|
|
19
8
|
source?: string;
|
|
20
9
|
title?: string;
|
|
21
10
|
};
|
|
22
11
|
export declare const generatePolicyMarkdown: (policy: Policy, options?: PolicyMarkdownOptions) => string;
|
|
23
12
|
export type DescribePolicyOptions = {
|
|
24
|
-
/** Instructions ride in
|
|
13
|
+
/** Instructions ride in every context, so this stays bounded. */
|
|
25
14
|
maxRules?: number;
|
|
26
15
|
playbook?: Playbook;
|
|
27
16
|
rules?: readonly PolicyRule[];
|
|
28
17
|
};
|
|
29
|
-
/**
|
|
30
|
-
* The same policy, bounded, for the channel an agent is handed when it connects.
|
|
31
|
-
*
|
|
32
|
-
* Persisting policy is only half the job: an agent that has to discover the rules by tripping over
|
|
33
|
-
* them will trip over them in front of a customer.
|
|
34
|
-
*/
|
|
35
18
|
export declare const describePolicy: (policy: Policy, options?: DescribePolicyOptions) => string;
|
package/dist/markdown.d.ts
CHANGED
|
@@ -1,35 +1,18 @@
|
|
|
1
1
|
import type { Playbook } from './learning.js';
|
|
2
2
|
import type { Policy, PolicyRule } from './types.js';
|
|
3
|
-
/**
|
|
4
|
-
* The policy as prose, generated beside the data it renders.
|
|
5
|
-
*
|
|
6
|
-
* musa checks in `policy/policy.json` and a `POLICY.md` written from it on every change, and the
|
|
7
|
-
* argument for generating rather than writing it is in that file's own history: two of its sections
|
|
8
|
-
* were prose, and both had gone stale and were telling agents the opposite of what the code did. A
|
|
9
|
-
* markdown that has to be remembered separately drifts, and a drifted one is worse than none — it
|
|
10
|
-
* reads authoritative while the engine enforces something else.
|
|
11
|
-
*
|
|
12
|
-
* So every count, every precedence sentence and every honesty report below is DERIVED.
|
|
13
|
-
*/
|
|
3
|
+
/** Generated beside the data it renders: hand-written sections went stale and told agents the opposite of what the engine enforced. Every count, precedence sentence and honesty report is derived. */
|
|
14
4
|
export type PolicyMarkdownOptions = {
|
|
15
5
|
generator?: string;
|
|
16
6
|
playbook?: Playbook;
|
|
17
7
|
rules?: readonly PolicyRule[];
|
|
18
|
-
/** What a reader should edit instead of this file. */
|
|
19
8
|
source?: string;
|
|
20
9
|
title?: string;
|
|
21
10
|
};
|
|
22
11
|
export declare const generatePolicyMarkdown: (policy: Policy, options?: PolicyMarkdownOptions) => string;
|
|
23
12
|
export type DescribePolicyOptions = {
|
|
24
|
-
/** Instructions ride in
|
|
13
|
+
/** Instructions ride in every context, so this stays bounded. */
|
|
25
14
|
maxRules?: number;
|
|
26
15
|
playbook?: Playbook;
|
|
27
16
|
rules?: readonly PolicyRule[];
|
|
28
17
|
};
|
|
29
|
-
/**
|
|
30
|
-
* The same policy, bounded, for the channel an agent is handed when it connects.
|
|
31
|
-
*
|
|
32
|
-
* Persisting policy is only half the job: an agent that has to discover the rules by tripping over
|
|
33
|
-
* them will trip over them in front of a customer.
|
|
34
|
-
*/
|
|
35
18
|
export declare const describePolicy: (policy: Policy, options?: DescribePolicyOptions) => string;
|
package/dist/medusa/index.cjs
CHANGED
|
@@ -47,37 +47,22 @@ __export(exports_medusa, {
|
|
|
47
47
|
module.exports = __toCommonJS(exports_medusa);
|
|
48
48
|
var import_rows = require("../rows.cjs");
|
|
49
49
|
var configRow = (namespace, key) => (store) => store.get(namespace, key, undefined);
|
|
50
|
-
var defaultRow = (entry, eventPrefix) => ({
|
|
51
|
-
actor_kind: "system",
|
|
52
|
-
...entry.rejected ? { error: `rejected ${JSON.stringify(entry.rejected.value)}: ${entry.rejected.reason}` } : {},
|
|
53
|
-
event_name: `${eventPrefix}${entry.event}`,
|
|
54
|
-
fell_back_to: { constraintKind: entry.kind, value: entry.fellBackTo },
|
|
55
|
-
...entry.op ? { op: entry.op } : {},
|
|
56
|
-
...entry.subject ? { subject: entry.subject } : {}
|
|
57
|
-
});
|
|
58
|
-
var attempt = async (what) => {
|
|
59
|
-
try {
|
|
60
|
-
return await what();
|
|
61
|
-
} catch {
|
|
62
|
-
return;
|
|
63
|
-
}
|
|
64
|
-
};
|
|
65
50
|
var createMedusaPolicyAdapter = (options) => {
|
|
66
51
|
const bindings = options.bindings ?? {};
|
|
67
52
|
const eventPrefix = options.eventPrefix ?? "";
|
|
68
|
-
const toRow = options.toRow ??
|
|
53
|
+
const toRow = options.toRow ?? import_rows.toJournalRow;
|
|
69
54
|
const service = () => options.container.resolve(options.moduleKey);
|
|
70
55
|
const store = () => options.container.resolve(options.configStoreKey ?? "configStore");
|
|
71
56
|
return {
|
|
72
57
|
config: {
|
|
73
58
|
get: async (kind, query) => {
|
|
74
59
|
const binding = bindings[kind];
|
|
75
|
-
return binding ? attempt(() => binding(store(), query)) : undefined;
|
|
60
|
+
return binding ? import_rows.attempt(() => binding(store(), query)) : undefined;
|
|
76
61
|
}
|
|
77
62
|
},
|
|
78
63
|
journal: {
|
|
79
64
|
write: async (entry) => {
|
|
80
|
-
await attempt(() => service().createPolicyJournalEntries?.(toRow(entry, eventPrefix)));
|
|
65
|
+
await import_rows.attempt(() => service().createPolicyJournalEntries?.(toRow(entry, eventPrefix)));
|
|
81
66
|
}
|
|
82
67
|
},
|
|
83
68
|
name: `medusa:${options.moduleKey}`,
|
package/dist/medusa/index.d.cts
CHANGED
|
@@ -1,79 +1,38 @@
|
|
|
1
1
|
import type { PermissionAction } from '../permissions/index.cjs';
|
|
2
2
|
import type { Awaitable, PolicyAdapter, PolicyJournalEntry, PolicyQuery, PolicyRule, PolicyRuleRow } from '../types.cjs';
|
|
3
|
-
/**
|
|
4
|
-
* The Medusa store, behind the ports the kernel reads.
|
|
5
|
-
*
|
|
6
|
-
* Nothing here imports `@medusajs/*`. The container is a thing the runtime hands the caller, so it
|
|
7
|
-
* arrives as an argument — which is also what makes every check in the conformance suite runnable
|
|
8
|
-
* without a booted server, and what let the 219 lines of resolution logic this package extracted
|
|
9
|
-
* stop dragging a module, a service and three ORM models behind them.
|
|
10
|
-
*/
|
|
11
|
-
/** The bit of the container this needs — structural, so a plain object stands in for it. */
|
|
3
|
+
/** Imports no `@medusajs/*`: the container arrives as an argument, so the conformance suite runs without a booted server. */
|
|
12
4
|
export type MedusaContainerLike = {
|
|
13
5
|
resolve: (key: string) => unknown;
|
|
14
6
|
};
|
|
15
|
-
/** The bit of the module service this needs: the generated list, and the generated create. */
|
|
16
7
|
export type MedusaPolicyServiceLike = {
|
|
17
8
|
createPolicyJournalEntries?: (data: Record<string, unknown>) => Awaitable<unknown>;
|
|
18
9
|
listPolicyRules?: (filter: Record<string, unknown>) => Awaitable<readonly PolicyRuleRow[]>;
|
|
19
10
|
};
|
|
20
|
-
/** The bit of a runtime-config service this needs. Its `get` answers with the fallback it is given. */
|
|
21
11
|
export type ConfigStoreLike = {
|
|
22
12
|
get: <T>(namespace: string, key: string, fallback: T) => Awaitable<T>;
|
|
23
13
|
};
|
|
24
14
|
export type ConfigStoreBinding = (store: ConfigStoreLike, query: PolicyQuery) => Awaitable<unknown>;
|
|
25
|
-
/**
|
|
26
|
-
* One row of the runtime config, as the value of one kind.
|
|
27
|
-
*
|
|
28
|
-
* The fallback handed to `get` is `undefined` on purpose: the service answers with whatever it is
|
|
29
|
-
* given when no row exists, so the only way to tell an unset row from a row holding that same value
|
|
30
|
-
* is to hand it something no row can legitimately hold. Junk in the row is not filtered here — the
|
|
31
|
-
* KIND's schema refuses it, once, for every layer that could produce one.
|
|
32
|
-
*/
|
|
15
|
+
/** The fallback handed to `get` is `undefined` on purpose: the service answers with whatever it is given when no row exists, so that is the only way to tell an unset row from one holding the fallback. Junk in the row is refused by the kind's schema, once, for every layer. */
|
|
33
16
|
export declare const configRow: (namespace: string, key: string) => ConfigStoreBinding;
|
|
34
17
|
export type MedusaPolicyAdapterOptions = {
|
|
35
|
-
/** Which config rows stand for which kind. A kind with no binding has no admin-set value. */
|
|
36
18
|
bindings?: Record<string, ConfigStoreBinding>;
|
|
37
19
|
configStoreKey?: string;
|
|
38
20
|
container: MedusaContainerLike;
|
|
39
|
-
/** What that store calls its own events, e.g. `rules_engine.`. */
|
|
40
21
|
eventPrefix?: string;
|
|
41
|
-
/** Rules from somewhere other than the table — a learned playbook's, appended LAST. */
|
|
42
22
|
extraRules?: () => Awaitable<readonly PolicyRule[]>;
|
|
43
23
|
moduleKey: string;
|
|
44
|
-
/** The row this store keeps. Overridden when its columns are not these. */
|
|
45
24
|
toRow?: (entry: PolicyJournalEntry, eventPrefix: string) => Record<string, unknown>;
|
|
46
25
|
};
|
|
47
26
|
export declare const createMedusaPolicyAdapter: (options: MedusaPolicyAdapterOptions) => PolicyAdapter;
|
|
48
|
-
/** One role as that module holds it: an id, and the policies granted to it. */
|
|
49
27
|
export type MedusaRbacRole = {
|
|
50
28
|
id: string;
|
|
51
29
|
policies?: readonly PermissionAction[];
|
|
52
30
|
};
|
|
53
|
-
/**
|
|
54
|
-
* The native RBAC module's roles, as grants the permission lattice can read.
|
|
55
|
-
*
|
|
56
|
-
* This is the whole bridge. Upstream's `hasPermission` fetches these itself through the container
|
|
57
|
-
* and a cache, which is why nothing that uses it can be answered without a booted server; the fetch
|
|
58
|
-
* is the caller's here, and the decision is a value.
|
|
59
|
-
*/
|
|
31
|
+
/** Upstream's `hasPermission` fetches grants through the container and a cache; here the fetch is the caller's and the decision is a value. */
|
|
60
32
|
export declare const medusaGrants: (roles: readonly MedusaRbacRole[]) => Record<string, readonly PermissionAction[]>;
|
|
61
|
-
/**
|
|
62
|
-
* The signature a middleware advertises, deliberately NOT the framework's `MiddlewareFunction`.
|
|
63
|
-
*
|
|
64
|
-
* That type carries `#private` class fields, so two copies of `@medusajs/framework` in one store
|
|
65
|
-
* make the same shape nominally incompatible and every `defineMiddlewares` call site goes red.
|
|
66
|
-
* `unknown` params are contravariant-safe: this assigns to every version's, and the runtime value
|
|
67
|
-
* is unchanged.
|
|
68
|
-
*/
|
|
33
|
+
/** Deliberately not the framework's `MiddlewareFunction`: it carries `#private` fields, so two copies of `@medusajs/framework` make the same shape nominally incompatible. `unknown` params assign to every version's. */
|
|
69
34
|
export type PortableMiddleware = (request: unknown, response: unknown, next: (error?: unknown) => void) => unknown;
|
|
70
35
|
type Wrapper = (handler: PortableMiddleware, policies: PermissionAction[]) => PortableMiddleware;
|
|
71
|
-
/**
|
|
72
|
-
* The framework's own permission check as a one-liner a route array can hold.
|
|
73
|
-
*
|
|
74
|
-
* The wrapper is passed in rather than imported, for the same reason the container is: a package
|
|
75
|
-
* that imported it would be unusable anywhere else, and would pin one of the two framework copies.
|
|
76
|
-
* The wrapped handler does nothing but continue — the wrapper itself is the gate.
|
|
77
|
-
*/
|
|
36
|
+
/** The wrapper is passed in, not imported, so this package neither pins one of two framework copies nor becomes unusable elsewhere. The wrapped handler only continues; the wrapper is the gate. */
|
|
78
37
|
export declare const requirePermission: (wrap: Wrapper, ...policies: PermissionAction[]) => PortableMiddleware;
|
|
79
38
|
export {};
|
package/dist/medusa/index.d.ts
CHANGED
|
@@ -1,79 +1,38 @@
|
|
|
1
1
|
import type { PermissionAction } from '../permissions/index.js';
|
|
2
2
|
import type { Awaitable, PolicyAdapter, PolicyJournalEntry, PolicyQuery, PolicyRule, PolicyRuleRow } from '../types.js';
|
|
3
|
-
/**
|
|
4
|
-
* The Medusa store, behind the ports the kernel reads.
|
|
5
|
-
*
|
|
6
|
-
* Nothing here imports `@medusajs/*`. The container is a thing the runtime hands the caller, so it
|
|
7
|
-
* arrives as an argument — which is also what makes every check in the conformance suite runnable
|
|
8
|
-
* without a booted server, and what let the 219 lines of resolution logic this package extracted
|
|
9
|
-
* stop dragging a module, a service and three ORM models behind them.
|
|
10
|
-
*/
|
|
11
|
-
/** The bit of the container this needs — structural, so a plain object stands in for it. */
|
|
3
|
+
/** Imports no `@medusajs/*`: the container arrives as an argument, so the conformance suite runs without a booted server. */
|
|
12
4
|
export type MedusaContainerLike = {
|
|
13
5
|
resolve: (key: string) => unknown;
|
|
14
6
|
};
|
|
15
|
-
/** The bit of the module service this needs: the generated list, and the generated create. */
|
|
16
7
|
export type MedusaPolicyServiceLike = {
|
|
17
8
|
createPolicyJournalEntries?: (data: Record<string, unknown>) => Awaitable<unknown>;
|
|
18
9
|
listPolicyRules?: (filter: Record<string, unknown>) => Awaitable<readonly PolicyRuleRow[]>;
|
|
19
10
|
};
|
|
20
|
-
/** The bit of a runtime-config service this needs. Its `get` answers with the fallback it is given. */
|
|
21
11
|
export type ConfigStoreLike = {
|
|
22
12
|
get: <T>(namespace: string, key: string, fallback: T) => Awaitable<T>;
|
|
23
13
|
};
|
|
24
14
|
export type ConfigStoreBinding = (store: ConfigStoreLike, query: PolicyQuery) => Awaitable<unknown>;
|
|
25
|
-
/**
|
|
26
|
-
* One row of the runtime config, as the value of one kind.
|
|
27
|
-
*
|
|
28
|
-
* The fallback handed to `get` is `undefined` on purpose: the service answers with whatever it is
|
|
29
|
-
* given when no row exists, so the only way to tell an unset row from a row holding that same value
|
|
30
|
-
* is to hand it something no row can legitimately hold. Junk in the row is not filtered here — the
|
|
31
|
-
* KIND's schema refuses it, once, for every layer that could produce one.
|
|
32
|
-
*/
|
|
15
|
+
/** The fallback handed to `get` is `undefined` on purpose: the service answers with whatever it is given when no row exists, so that is the only way to tell an unset row from one holding the fallback. Junk in the row is refused by the kind's schema, once, for every layer. */
|
|
33
16
|
export declare const configRow: (namespace: string, key: string) => ConfigStoreBinding;
|
|
34
17
|
export type MedusaPolicyAdapterOptions = {
|
|
35
|
-
/** Which config rows stand for which kind. A kind with no binding has no admin-set value. */
|
|
36
18
|
bindings?: Record<string, ConfigStoreBinding>;
|
|
37
19
|
configStoreKey?: string;
|
|
38
20
|
container: MedusaContainerLike;
|
|
39
|
-
/** What that store calls its own events, e.g. `rules_engine.`. */
|
|
40
21
|
eventPrefix?: string;
|
|
41
|
-
/** Rules from somewhere other than the table — a learned playbook's, appended LAST. */
|
|
42
22
|
extraRules?: () => Awaitable<readonly PolicyRule[]>;
|
|
43
23
|
moduleKey: string;
|
|
44
|
-
/** The row this store keeps. Overridden when its columns are not these. */
|
|
45
24
|
toRow?: (entry: PolicyJournalEntry, eventPrefix: string) => Record<string, unknown>;
|
|
46
25
|
};
|
|
47
26
|
export declare const createMedusaPolicyAdapter: (options: MedusaPolicyAdapterOptions) => PolicyAdapter;
|
|
48
|
-
/** One role as that module holds it: an id, and the policies granted to it. */
|
|
49
27
|
export type MedusaRbacRole = {
|
|
50
28
|
id: string;
|
|
51
29
|
policies?: readonly PermissionAction[];
|
|
52
30
|
};
|
|
53
|
-
/**
|
|
54
|
-
* The native RBAC module's roles, as grants the permission lattice can read.
|
|
55
|
-
*
|
|
56
|
-
* This is the whole bridge. Upstream's `hasPermission` fetches these itself through the container
|
|
57
|
-
* and a cache, which is why nothing that uses it can be answered without a booted server; the fetch
|
|
58
|
-
* is the caller's here, and the decision is a value.
|
|
59
|
-
*/
|
|
31
|
+
/** Upstream's `hasPermission` fetches grants through the container and a cache; here the fetch is the caller's and the decision is a value. */
|
|
60
32
|
export declare const medusaGrants: (roles: readonly MedusaRbacRole[]) => Record<string, readonly PermissionAction[]>;
|
|
61
|
-
/**
|
|
62
|
-
* The signature a middleware advertises, deliberately NOT the framework's `MiddlewareFunction`.
|
|
63
|
-
*
|
|
64
|
-
* That type carries `#private` class fields, so two copies of `@medusajs/framework` in one store
|
|
65
|
-
* make the same shape nominally incompatible and every `defineMiddlewares` call site goes red.
|
|
66
|
-
* `unknown` params are contravariant-safe: this assigns to every version's, and the runtime value
|
|
67
|
-
* is unchanged.
|
|
68
|
-
*/
|
|
33
|
+
/** Deliberately not the framework's `MiddlewareFunction`: it carries `#private` fields, so two copies of `@medusajs/framework` make the same shape nominally incompatible. `unknown` params assign to every version's. */
|
|
69
34
|
export type PortableMiddleware = (request: unknown, response: unknown, next: (error?: unknown) => void) => unknown;
|
|
70
35
|
type Wrapper = (handler: PortableMiddleware, policies: PermissionAction[]) => PortableMiddleware;
|
|
71
|
-
/**
|
|
72
|
-
* The framework's own permission check as a one-liner a route array can hold.
|
|
73
|
-
*
|
|
74
|
-
* The wrapper is passed in rather than imported, for the same reason the container is: a package
|
|
75
|
-
* that imported it would be unusable anywhere else, and would pin one of the two framework copies.
|
|
76
|
-
* The wrapped handler does nothing but continue — the wrapper itself is the gate.
|
|
77
|
-
*/
|
|
36
|
+
/** The wrapper is passed in, not imported, so this package neither pins one of two framework copies nor becomes unusable elsewhere. The wrapped handler only continues; the wrapper is the gate. */
|
|
78
37
|
export declare const requirePermission: (wrap: Wrapper, ...policies: PermissionAction[]) => PortableMiddleware;
|
|
79
38
|
export {};
|
package/dist/medusa/index.js
CHANGED
|
@@ -1,25 +1,10 @@
|
|
|
1
1
|
// src/medusa/index.ts
|
|
2
|
-
import { toPolicyRules } from "../rows.js";
|
|
2
|
+
import { attempt, toJournalRow, toPolicyRules } from "../rows.js";
|
|
3
3
|
var configRow = (namespace, key) => (store) => store.get(namespace, key, undefined);
|
|
4
|
-
var defaultRow = (entry, eventPrefix) => ({
|
|
5
|
-
actor_kind: "system",
|
|
6
|
-
...entry.rejected ? { error: `rejected ${JSON.stringify(entry.rejected.value)}: ${entry.rejected.reason}` } : {},
|
|
7
|
-
event_name: `${eventPrefix}${entry.event}`,
|
|
8
|
-
fell_back_to: { constraintKind: entry.kind, value: entry.fellBackTo },
|
|
9
|
-
...entry.op ? { op: entry.op } : {},
|
|
10
|
-
...entry.subject ? { subject: entry.subject } : {}
|
|
11
|
-
});
|
|
12
|
-
var attempt = async (what) => {
|
|
13
|
-
try {
|
|
14
|
-
return await what();
|
|
15
|
-
} catch {
|
|
16
|
-
return;
|
|
17
|
-
}
|
|
18
|
-
};
|
|
19
4
|
var createMedusaPolicyAdapter = (options) => {
|
|
20
5
|
const bindings = options.bindings ?? {};
|
|
21
6
|
const eventPrefix = options.eventPrefix ?? "";
|
|
22
|
-
const toRow = options.toRow ??
|
|
7
|
+
const toRow = options.toRow ?? toJournalRow;
|
|
23
8
|
const service = () => options.container.resolve(options.moduleKey);
|
|
24
9
|
const store = () => options.container.resolve(options.configStoreKey ?? "configStore");
|
|
25
10
|
return {
|
|
@@ -54,7 +54,7 @@ var WILDCARD = "*";
|
|
|
54
54
|
var permissionKey = (resource, operation) => `${resource}:${operation}`;
|
|
55
55
|
var normalizePolicyKey = (key) => key === WILDCARD ? WILDCARD : key.replace(/([a-z])([A-Z])/g, "$1_$2").replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
|
|
56
56
|
var definePolicies = (policies, options = {}) => {
|
|
57
|
-
const declared =
|
|
57
|
+
const declared = asArray(policies);
|
|
58
58
|
const normalize = options.normalize ?? normalizePolicyKey;
|
|
59
59
|
return {
|
|
60
60
|
policies: declared.map((policy) => {
|
|
@@ -93,15 +93,19 @@ var createPolicyCatalog = (options = {}) => {
|
|
|
93
93
|
var expandPolicies = (actions) => {
|
|
94
94
|
const byKey = new Map;
|
|
95
95
|
for (const action of actions) {
|
|
96
|
-
const
|
|
97
|
-
for (const operation of operations) {
|
|
96
|
+
for (const operation of asArray(action.operation)) {
|
|
98
97
|
const key = permissionKey(action.resource, operation);
|
|
99
98
|
byKey.set(key, { key, operation, resource: action.resource });
|
|
100
99
|
}
|
|
101
100
|
}
|
|
102
101
|
return [...byKey.values()];
|
|
103
102
|
};
|
|
104
|
-
var
|
|
103
|
+
var isMap = (grants) => grants instanceof Map;
|
|
104
|
+
var grantsFor = (grants, role) => {
|
|
105
|
+
if (isMap(grants))
|
|
106
|
+
return grants.get(role) ?? [];
|
|
107
|
+
return Object.hasOwn(grants, role) ? grants[role] ?? [] : [];
|
|
108
|
+
};
|
|
105
109
|
var asArray = (value) => Array.isArray(value) ? value : [value];
|
|
106
110
|
var policyAllows = (grants, roles, resource, operation) => roles.some((role) => {
|
|
107
111
|
const allowed = new Set(expandPolicies(grantsFor(grants, role)).filter((policy) => policy.resource === resource || policy.resource === WILDCARD).map((policy) => policy.operation));
|
|
@@ -1,16 +1,4 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* A permission lattice — Medusa 2.19.0's `definePolicies` / `hasPermission` / `resolvePermissions`
|
|
3
|
-
* with the container lifted out.
|
|
4
|
-
*
|
|
5
|
-
* A Medusa storefront did not reinvent permissions and was right not to: it adopted the native
|
|
6
|
-
* module and put a typed registry in front of it. What that registry could not be given was a way
|
|
7
|
-
* to ANSWER the question without a booted container — so the same 22 named policies are
|
|
8
|
-
* unit-testable in node and the check they feed is not. Everything here is pure: the grants are
|
|
9
|
-
* data the caller fetched, and the answer is a value.
|
|
10
|
-
*
|
|
11
|
-
* Every semantic is pinned from the shipped implementation. No test file ships in either tarball.
|
|
12
|
-
*/
|
|
13
|
-
/** The single character used as the wildcard in BOTH the resource and the operation slot. */
|
|
1
|
+
/** Medusa 2.19.0's `definePolicies` / `hasPermission` / `resolvePermissions` with the container lifted out, so the answer is a value that unit-tests without a booted server. */
|
|
14
2
|
export declare const WILDCARD = "*";
|
|
15
3
|
export type PolicyDefinition = {
|
|
16
4
|
description?: string;
|
|
@@ -18,40 +6,23 @@ export type PolicyDefinition = {
|
|
|
18
6
|
operation: string;
|
|
19
7
|
resource: string;
|
|
20
8
|
};
|
|
21
|
-
/** A resource with one or more operations on it — what a route asks for. */
|
|
22
9
|
export type PermissionAction = {
|
|
23
10
|
operation: readonly string[] | string;
|
|
24
11
|
resource: string;
|
|
25
12
|
};
|
|
26
|
-
/** A single (resource, operation) pair with the key a store would hold it under. */
|
|
27
13
|
export type ExpandedPolicy = {
|
|
28
14
|
key: string;
|
|
29
15
|
operation: string;
|
|
30
16
|
resource: string;
|
|
31
17
|
};
|
|
32
|
-
/** What each role has been granted. The caller fetched it; this decides with it. */
|
|
33
18
|
export type PolicyGrants = ReadonlyMap<string, readonly PermissionAction[]> | Readonly<Record<string, readonly PermissionAction[]>>;
|
|
34
19
|
export declare const permissionKey: (resource: string, operation: string) => string;
|
|
35
|
-
/**
|
|
36
|
-
* `ReadBrands` → `read_brands`, and the wildcard through untouched.
|
|
37
|
-
*
|
|
38
|
-
* Exported because a repo has to be able to check its own vocabulary against it: an operation
|
|
39
|
-
* spelled `certificate:create` normalises to `certificate_create`, so a repo that authors its rows
|
|
40
|
-
* directly (as a Medusa storefront does) and ALSO declares them through here would end up with two
|
|
41
|
-
* spellings of one permission and no error anywhere.
|
|
42
|
-
*/
|
|
20
|
+
/** Exported so a repo can check its vocabulary: `certificate:create` normalises to `certificate_create`, so authoring rows directly and also declaring through here yields two spellings of one permission. */
|
|
43
21
|
export declare const normalizePolicyKey: (key: string) => string;
|
|
44
22
|
export type DefinePoliciesOptions = {
|
|
45
23
|
normalize?: (key: string) => string;
|
|
46
24
|
};
|
|
47
|
-
/**
|
|
48
|
-
* Declare policies. Answers with them; registers nothing globally.
|
|
49
|
-
*
|
|
50
|
-
* Upstream writes into three `globalThis` registries and REWRITES the caller's objects in place, so
|
|
51
|
-
* the array you passed comes back normalised under you and a second file declaring the same name
|
|
52
|
-
* silently replaces the first. Neither is load-bearing for the decision, and both are surprising, so
|
|
53
|
-
* neither is reproduced — `createPolicyCatalog` is the registry, and it refuses a duplicate.
|
|
54
|
-
*/
|
|
25
|
+
/** Upstream writes into three `globalThis` registries and rewrites the caller's objects in place; neither is reproduced. `createPolicyCatalog` is the registry and refuses a duplicate. */
|
|
55
26
|
export declare const definePolicies: (policies: PolicyDefinition | readonly PolicyDefinition[], options?: DefinePoliciesOptions) => {
|
|
56
27
|
policies: PolicyDefinition[];
|
|
57
28
|
};
|
|
@@ -62,63 +33,33 @@ export type PolicyCatalog = {
|
|
|
62
33
|
operations: () => string[];
|
|
63
34
|
resources: () => string[];
|
|
64
35
|
};
|
|
65
|
-
/** The registry upstream keeps globally, made local and made to refuse a name already taken. */
|
|
66
36
|
export declare const createPolicyCatalog: (options?: DefinePoliciesOptions) => PolicyCatalog;
|
|
67
|
-
/**
|
|
68
|
-
* Expand actions into the unique one-operation rows a store keeps, deduped, key derived.
|
|
69
|
-
*
|
|
70
|
-
* The key is `<resource>:<operation>` on the RAW operation, which is how a wildcard grant becomes
|
|
71
|
-
* the single `*:*` row that authorises every route — granting the union of a repo's own named
|
|
72
|
-
* policies instead covers its custom resources only, and 403s every native one.
|
|
73
|
-
*/
|
|
37
|
+
/** Keyed `<resource>:<operation>` on the raw operation, so a wildcard grant is the single `*:*` row; granting the union of a repo's named policies would 403 every native route. */
|
|
74
38
|
export declare const expandPolicies: (actions: readonly PermissionAction[]) => ExpandedPolicy[];
|
|
75
39
|
export type HasPermissionInput = {
|
|
76
40
|
actions: PermissionAction | readonly PermissionAction[];
|
|
77
|
-
/**
|
|
78
|
-
* Whether the mechanism is on at all. `false` allows everything, which is what the `rbac` feature
|
|
79
|
-
* flag does upstream — and it is off by default there.
|
|
80
|
-
*/
|
|
41
|
+
/** `false` allows everything, as upstream's `rbac` feature flag does (off by default there). */
|
|
81
42
|
enabled?: boolean;
|
|
82
43
|
grants: PolicyGrants;
|
|
83
|
-
/**
|
|
84
|
-
* What an actor with NO roles gets. Upstream's `hasPermission` allows (`!roleIds?.length` returns
|
|
85
|
-
* true) while its own route wrapper denies, so the same request gets opposite answers depending
|
|
86
|
-
* on which door it came through. `allow` is upstream's answer here.
|
|
87
|
-
*/
|
|
44
|
+
/** Upstream's `hasPermission` allows a role-less actor while its route wrapper denies, so one request gets opposite answers by door. `allow` is upstream's answer here. */
|
|
88
45
|
onEmptyRoles?: 'allow' | 'deny';
|
|
89
46
|
roles: readonly string[] | string;
|
|
90
47
|
};
|
|
91
|
-
/** Do these roles grant every one of these actions? */
|
|
92
48
|
export declare const hasPermission: (input: HasPermissionInput) => boolean;
|
|
93
49
|
export type ResolvePermissionsInput = {
|
|
94
50
|
enabled?: boolean;
|
|
95
51
|
grants: PolicyGrants;
|
|
96
52
|
roles: readonly string[] | string;
|
|
97
|
-
/** The (resource, operation) pairs to evaluate against, with wildcards expanded into them. */
|
|
98
53
|
universe: readonly {
|
|
99
54
|
operation: string;
|
|
100
55
|
resource: string;
|
|
101
56
|
}[];
|
|
102
57
|
};
|
|
103
|
-
/**
|
|
104
|
-
* The subset of the universe these roles are granted, keyed `resource:operation`.
|
|
105
|
-
*
|
|
106
|
-
* The inverse of `hasPermission`, for a client that would otherwise have to re-implement wildcard
|
|
107
|
-
* semantics to render a menu. Note the asymmetry, which is upstream's: with the mechanism off this
|
|
108
|
-
* answers with EVERYTHING, and for an actor with no roles it answers with NOTHING — where
|
|
109
|
-
* `hasPermission` answers true for that same actor.
|
|
110
|
-
*/
|
|
58
|
+
/** Inverse of `hasPermission`. With the mechanism off it answers everything, and for a role-less actor nothing, where `hasPermission` answers true: upstream's asymmetry. */
|
|
111
59
|
export declare const resolvePermissions: (input: ResolvePermissionsInput) => Set<string>;
|
|
112
60
|
export type PermissionCheck = {
|
|
113
61
|
allowed: boolean;
|
|
114
62
|
required: string[];
|
|
115
63
|
};
|
|
116
|
-
/**
|
|
117
|
-
* The decision a route guard needs: the answer, plus WHICH permissions were required.
|
|
118
|
-
*
|
|
119
|
-
* A refusal that names them teaches the person blocked by it something; one that says "Forbidden"
|
|
120
|
-
* sends them to whoever owns the roles table. Denies a role-less actor, as the route wrapper does —
|
|
121
|
-
* but unlike the wrapper it still honours the flag, which the wrapper reads only after it has
|
|
122
|
-
* already thrown.
|
|
123
|
-
*/
|
|
64
|
+
/** Names the required permissions in the refusal. Denies a role-less actor like the route wrapper, but honours the flag, which the wrapper reads only after throwing. */
|
|
124
65
|
export declare const checkPermissions: (input: Omit<HasPermissionInput, 'onEmptyRoles'>) => PermissionCheck;
|