@fabricorg/policy-opa 0.1.0 → 0.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 +17 -0
- package/README.md +46 -10
- package/dist/index.cjs +138 -14
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +174 -11
- package/dist/index.d.ts +174 -11
- package/dist/index.js +136 -15
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# @fabricorg/policy-opa
|
|
2
2
|
|
|
3
|
+
## 0.2.0 — 2026-05-16
|
|
4
|
+
|
|
5
|
+
### Minor
|
|
6
|
+
|
|
7
|
+
- **Rich execution provenance.** Adds an `OpaPolicyExecutor` shape (`execute(path, input) → OpaPolicyExecution`) alongside the existing `OpaPolicyClient` (`evaluate(path, input)`). The factory detects either shape on `ctx.services[serviceKey]` and prefers `execute` when both are present. Lets adapter callers surface OPA's `decision_id`, `provenance.version`, and `provenance.bundles[*].revision` — fields the high-level `@open-policy-agent/opa` SDK discards.
|
|
8
|
+
- **`executorFromOpaHttp({ baseUrl, fetch?, headers?, provenance? })`** — official executor that POSTs to `{baseUrl}/v1/data/{path}?provenance=true`, parses the snake_case OPA response, and surfaces full provenance. Zero runtime deps; works on Node 20+ (uses `globalThis.fetch`), and on any runtime by passing a custom `fetch` implementation. Recommended for production deployments that need audit-grade evidence.
|
|
9
|
+
- **`executorFromOpaClient(client)`** — wraps the high-level SDK as an `OpaPolicyExecutor` for hosts that want to standardize on the executor interface even while accepting the limited provenance the SDK exposes.
|
|
10
|
+
- **`OpaPolicyBinding.bundleName?`** — optional selector for `provenance.bundles[name].revision`. Selection rules: explicit `bundleName` wins; otherwise a single-bundle response is used unambiguously; multiple bundles without a selector are recorded as `engine.metadata.bundleRevisionStatus: "ambiguous"` so audit dashboards can flag policies that need explicit selectors.
|
|
11
|
+
- **`engine.metadata` richer fields.** When the executor surfaces them, `dispatchEvidence.engine.metadata` now carries `decisionId`, `bundleName`, `bundleRevision`, `bundleRevisionStatus`, and the raw `provenance` block. `engine.version` is set from `provenance.version` when present, otherwise falls back to the `engineVersion` option.
|
|
12
|
+
- **`mapDecision` third argument.** `mapDecision: (decision, ctx, execution) => …` — the `execution` arg exposes `decisionId`, `bundleRevision`, `opaVersion`, and `provenance` so mappers can lift specific provenance fields into `outcome.metadata` if the host wants them queryable outside `dispatchEvidence`. Existing two-argument mappers from v0.1 continue to work (TypeScript permits implementations with fewer parameters).
|
|
13
|
+
- **Failure evidence now includes provenance** when available. A malformed-response failure under the executor path still records `decisionId` and `bundleRevision` in `engine.metadata` — useful for correlating "OPA returned something we couldn't parse" against OPA's own decision logs.
|
|
14
|
+
- **Tests:** 25 → 50. Added 25 covering: executor path with full provenance, single-bundle vs. multi-bundle vs. ambiguous selection, missing-provenance non-fatality, mapDecision third arg, service shape detection (executor preferred over client), bundle-selector unit tests, `executorFromOpaClient` wrapping, and `executorFromOpaHttp` URL construction / snake_case parsing / header forwarding / non-2xx handling.
|
|
15
|
+
|
|
16
|
+
### Backwards compatibility
|
|
17
|
+
|
|
18
|
+
All v0.1 surface area is preserved. Hosts wiring `ctx.services.opa` as an `OpaPolicyClient` (with `evaluate`) continue to work without code changes; they simply don't get OPA-side provenance in `engine.metadata`. Upgrade path is: swap the client for `executorFromOpaHttp(...)` to gain `decisionId` and `bundleRevision`, and add `bundleName` to bindings that target a specific OPA bundle.
|
|
19
|
+
|
|
3
20
|
## 0.1.0 — 2026-05-16
|
|
4
21
|
|
|
5
22
|
### Initial release
|
package/README.md
CHANGED
|
@@ -8,11 +8,16 @@ The platform stays zero-dependency and vendor-neutral; the OPA-specific glue liv
|
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
10
|
pnpm add @fabricorg/platform @fabricorg/policy-opa
|
|
11
|
-
#
|
|
11
|
+
# Optionally the official SDK if you want the high-level client shape:
|
|
12
12
|
pnpm add @open-policy-agent/opa
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
`@fabricorg/policy-opa` has **zero runtime dependencies**.
|
|
15
|
+
`@fabricorg/policy-opa` has **zero runtime dependencies**. Two wiring shapes are supported:
|
|
16
|
+
|
|
17
|
+
- **`OpaPolicyExecutor`** (recommended) — `execute(path, input) → OpaPolicyExecution`. Surfaces full OPA-side provenance (`decisionId`, `bundleRevision`, `opaVersion`, raw `provenance` block) under `engine.metadata`. The package ships `executorFromOpaHttp({ baseUrl, ... })` for this.
|
|
18
|
+
- **`OpaPolicyClient`** — `evaluate(path, input) → Promise<unknown>`. Structurally compatible with the high-level `@open-policy-agent/opa` SDK. Simpler to wire but the SDK discards `decisionId` and `provenance` from the response, so audit evidence is thinner.
|
|
19
|
+
|
|
20
|
+
If a service implements both methods, `execute` is preferred.
|
|
16
21
|
|
|
17
22
|
## Usage — the four pieces
|
|
18
23
|
|
|
@@ -20,7 +25,7 @@ A complete OPA-backed evaluator has four pieces, three of which the vertical own
|
|
|
20
25
|
|
|
21
26
|
### 1. The vertical policy manifest
|
|
22
27
|
|
|
23
|
-
Keep Fabric policy IDs, versions, decision paths,
|
|
28
|
+
Keep Fabric policy IDs, versions, decision paths, Rego package names, and bundle selectors in one place. Don't inline strings at call sites.
|
|
24
29
|
|
|
25
30
|
```ts
|
|
26
31
|
import type { OpaPolicyBinding } from "@fabricorg/policy-opa";
|
|
@@ -31,10 +36,13 @@ export const LENDING_POLICY_BINDINGS = {
|
|
|
31
36
|
version: 1,
|
|
32
37
|
decisionPath: "fabric/lending/tcpa/contact_window/decision",
|
|
33
38
|
regoPackage: "fabric.lending.tcpa.contact_window",
|
|
39
|
+
bundleName: "lending",
|
|
34
40
|
},
|
|
35
41
|
} satisfies Record<string, OpaPolicyBinding>;
|
|
36
42
|
```
|
|
37
43
|
|
|
44
|
+
`bundleName` is optional. Set it when your OPA serves multiple bundles and you need audit evidence to record exactly which bundle's revision produced the decision. If OPA serves only one bundle, omit `bundleName` and the adapter uses that bundle's revision unambiguously.
|
|
45
|
+
|
|
38
46
|
### 2. The fact builder (TypeScript)
|
|
39
47
|
|
|
40
48
|
Snapshot the facts OPA needs from your database. OPA never touches your DB directly — your TypeScript host owns reads, tenant scoping, and redaction.
|
|
@@ -117,12 +125,19 @@ registerPolicy(tcpaPolicy);
|
|
|
117
125
|
|
|
118
126
|
### Host wiring
|
|
119
127
|
|
|
120
|
-
The runtime host injects
|
|
128
|
+
The runtime host injects an OPA executor (or client) into `PolicyContext.services` when it builds a policy context.
|
|
129
|
+
|
|
130
|
+
**Recommended — HTTP executor with full provenance:**
|
|
121
131
|
|
|
122
132
|
```ts
|
|
123
|
-
import {
|
|
133
|
+
import { executorFromOpaHttp } from "@fabricorg/policy-opa";
|
|
124
134
|
|
|
125
|
-
const opa =
|
|
135
|
+
const opa = executorFromOpaHttp({
|
|
136
|
+
baseUrl: process.env.OPA_URL ?? "http://localhost:8181",
|
|
137
|
+
// provenance: true is the default — `?provenance=true` is appended to
|
|
138
|
+
// every request so OPA returns decision_id and bundle revisions.
|
|
139
|
+
// headers: { authorization: `Bearer ${process.env.OPA_TOKEN}` },
|
|
140
|
+
});
|
|
126
141
|
|
|
127
142
|
// when constructing PolicyContext for evaluatePolicyDefinitions:
|
|
128
143
|
const policyCtx = {
|
|
@@ -133,9 +148,21 @@ const policyCtx = {
|
|
|
133
148
|
};
|
|
134
149
|
```
|
|
135
150
|
|
|
151
|
+
**Alternative — wrap the high-level SDK:**
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
import { OPAClient } from "@open-policy-agent/opa";
|
|
155
|
+
import { executorFromOpaClient } from "@fabricorg/policy-opa";
|
|
156
|
+
|
|
157
|
+
const opa = executorFromOpaClient(new OPAClient(process.env.OPA_URL ?? "http://localhost:8181"));
|
|
158
|
+
// ... services: { opa }
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
This works (the adapter accepts an `OpaPolicyClient` directly too, so wrapping isn't strictly required), but the high-level SDK discards `decision_id` and `provenance` — audit evidence is thinner than with `executorFromOpaHttp`.
|
|
162
|
+
|
|
136
163
|
## What lands in audit evidence
|
|
137
164
|
|
|
138
|
-
For a successful OPA evaluation, `PolicyDispatchEvidence.engine` looks like:
|
|
165
|
+
For a successful OPA evaluation under the HTTP executor (with provenance enabled), `PolicyDispatchEvidence.engine` looks like:
|
|
139
166
|
|
|
140
167
|
```json
|
|
141
168
|
{
|
|
@@ -145,13 +172,22 @@ For a successful OPA evaluation, `PolicyDispatchEvidence.engine` looks like:
|
|
|
145
172
|
"decisionPath": "fabric/lending/tcpa/contact_window/decision",
|
|
146
173
|
"regoPackage": "fabric.lending.tcpa.contact_window",
|
|
147
174
|
"inputHash": "sha256:8a3c…",
|
|
175
|
+
"decisionId": "01J0Q9MZ…",
|
|
176
|
+
"bundleName": "lending",
|
|
177
|
+
"bundleRevision": "2026-05-16.3",
|
|
178
|
+
"provenance": {
|
|
179
|
+
"version": "0.65.0",
|
|
180
|
+
"bundles": { "lending": { "revision": "2026-05-16.3" } }
|
|
181
|
+
},
|
|
148
182
|
"conditionResults": [{ "conditionId": "consent_active", "passed": true, "result": "pass" }],
|
|
149
183
|
"factsUsed": { "consent": { "active": true } }
|
|
150
184
|
}
|
|
151
185
|
}
|
|
152
186
|
```
|
|
153
187
|
|
|
154
|
-
Fabric's `policyId` / `policyVersion` remain canonical (`"what was evaluated"`). `engine.metadata` answers `"which artifact produced the answer"
|
|
188
|
+
Fabric's `policyId` / `policyVersion` remain canonical (`"what was evaluated"`). `engine.metadata.{decisionId, bundleName, bundleRevision}` answers `"which artifact produced the answer"`, and `decisionId` is the join key against OPA's own decision-log stream if you ship it to a SIEM. All of this rides on the `PolicyEvaluation` row Fabric persists per outcome.
|
|
189
|
+
|
|
190
|
+
If OPA serves multiple bundles and the binding has no `bundleName` selector, `bundleRevision` is omitted and `bundleRevisionStatus: "ambiguous"` is recorded — audit dashboards can flag these for a manual fix.
|
|
155
191
|
|
|
156
192
|
## Failure modes
|
|
157
193
|
|
|
@@ -171,9 +207,9 @@ OPA evaluation is a network call, so the adapter defaults `previewSafe: false`.
|
|
|
171
207
|
## What this package does NOT do
|
|
172
208
|
|
|
173
209
|
- It doesn't talk to your database. `buildInput` is yours.
|
|
174
|
-
- It doesn't run an OPA server. You bring an OPA sidecar (or remote service) and inject
|
|
210
|
+
- It doesn't run an OPA server. You bring an OPA sidecar (or remote service) and inject an executor or client.
|
|
175
211
|
- It doesn't ship Rego policies. You author and bundle those.
|
|
176
|
-
- It doesn't
|
|
212
|
+
- It doesn't auto-discover bundle names. Bind one explicitly with `binding.bundleName` if OPA serves multiple bundles, or accept the `"ambiguous"` status in evidence.
|
|
177
213
|
|
|
178
214
|
## License
|
|
179
215
|
|
package/dist/index.cjs
CHANGED
|
@@ -2,6 +2,33 @@
|
|
|
2
2
|
|
|
3
3
|
var crypto = require('crypto');
|
|
4
4
|
|
|
5
|
+
// src/bundle-selector.ts
|
|
6
|
+
function selectBundleRevision(execution, binding) {
|
|
7
|
+
if (typeof execution.bundleRevision === "string" && execution.bundleRevision.length > 0) {
|
|
8
|
+
return { bundleRevision: execution.bundleRevision };
|
|
9
|
+
}
|
|
10
|
+
const bundles = readBundles(execution.provenance);
|
|
11
|
+
if (!bundles) return {};
|
|
12
|
+
const names = Object.keys(bundles);
|
|
13
|
+
if (names.length === 0) return {};
|
|
14
|
+
if (binding.bundleName) {
|
|
15
|
+
const revision = bundles[binding.bundleName]?.revision;
|
|
16
|
+
return typeof revision === "string" && revision.length > 0 ? { bundleRevision: revision } : {};
|
|
17
|
+
}
|
|
18
|
+
if (names.length === 1) {
|
|
19
|
+
const only = names[0];
|
|
20
|
+
const revision = only !== void 0 ? bundles[only]?.revision : void 0;
|
|
21
|
+
return typeof revision === "string" && revision.length > 0 ? { bundleRevision: revision } : {};
|
|
22
|
+
}
|
|
23
|
+
return { bundleRevisionStatus: "ambiguous" };
|
|
24
|
+
}
|
|
25
|
+
function readBundles(provenance) {
|
|
26
|
+
if (!provenance || typeof provenance !== "object") return void 0;
|
|
27
|
+
const b = provenance.bundles;
|
|
28
|
+
if (!b || typeof b !== "object" || Array.isArray(b)) return void 0;
|
|
29
|
+
return b;
|
|
30
|
+
}
|
|
31
|
+
|
|
5
32
|
// src/decision-schema.ts
|
|
6
33
|
var POLICY_RESULTS = ["pass", "warn", "block"];
|
|
7
34
|
function parseOpaDecision(raw) {
|
|
@@ -91,13 +118,14 @@ function createOpaPolicyEvaluator(options) {
|
|
|
91
118
|
version: binding.version,
|
|
92
119
|
previewSafe,
|
|
93
120
|
evaluate: async (ctx) => {
|
|
94
|
-
const
|
|
95
|
-
|
|
121
|
+
const service = ctx.services?.[serviceKey];
|
|
122
|
+
const transport = resolveTransport(service);
|
|
123
|
+
if (!transport) {
|
|
96
124
|
return makeFailureOutcome(
|
|
97
125
|
binding,
|
|
98
126
|
engineVersion,
|
|
99
127
|
"client_unavailable",
|
|
100
|
-
`No OPA client at ctx.services["${serviceKey}"]`,
|
|
128
|
+
`No OPA client/executor at ctx.services["${serviceKey}"]`,
|
|
101
129
|
onError
|
|
102
130
|
);
|
|
103
131
|
}
|
|
@@ -118,9 +146,9 @@ function createOpaPolicyEvaluator(options) {
|
|
|
118
146
|
inputHash = hashInput(input);
|
|
119
147
|
} catch {
|
|
120
148
|
}
|
|
121
|
-
let
|
|
149
|
+
let execution;
|
|
122
150
|
try {
|
|
123
|
-
|
|
151
|
+
execution = await transport(binding.decisionPath, input);
|
|
124
152
|
} catch (err) {
|
|
125
153
|
return makeFailureOutcome(
|
|
126
154
|
binding,
|
|
@@ -131,7 +159,7 @@ function createOpaPolicyEvaluator(options) {
|
|
|
131
159
|
inputHash
|
|
132
160
|
);
|
|
133
161
|
}
|
|
134
|
-
const parsed = parseOpaDecision(
|
|
162
|
+
const parsed = parseOpaDecision(execution.decision);
|
|
135
163
|
if (!parsed.ok) {
|
|
136
164
|
return makeFailureOutcome(
|
|
137
165
|
binding,
|
|
@@ -139,13 +167,15 @@ function createOpaPolicyEvaluator(options) {
|
|
|
139
167
|
"invalid_response",
|
|
140
168
|
`OPA returned malformed decision: ${parsed.error}`,
|
|
141
169
|
onError,
|
|
142
|
-
inputHash
|
|
170
|
+
inputHash,
|
|
171
|
+
execution
|
|
143
172
|
);
|
|
144
173
|
}
|
|
145
174
|
return buildSuccessOutcome(
|
|
146
175
|
binding,
|
|
147
176
|
engineVersion,
|
|
148
177
|
parsed.decision,
|
|
178
|
+
execution,
|
|
149
179
|
inputHash,
|
|
150
180
|
ctx,
|
|
151
181
|
mapDecision
|
|
@@ -153,13 +183,28 @@ function createOpaPolicyEvaluator(options) {
|
|
|
153
183
|
}
|
|
154
184
|
};
|
|
155
185
|
}
|
|
156
|
-
function
|
|
157
|
-
|
|
186
|
+
function resolveTransport(service) {
|
|
187
|
+
if (!service || typeof service !== "object") return null;
|
|
188
|
+
const exec = service.execute;
|
|
189
|
+
if (typeof exec === "function") {
|
|
190
|
+
return (path, input) => service.execute(path, input);
|
|
191
|
+
}
|
|
192
|
+
const eval_ = service.evaluate;
|
|
193
|
+
if (typeof eval_ === "function") {
|
|
194
|
+
return async (path, input) => ({
|
|
195
|
+
decision: await service.evaluate(path, input)
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
function buildSuccessOutcome(binding, engineVersion, decision, execution, inputHash, ctx, mapDecision) {
|
|
201
|
+
const selection = selectBundleRevision(execution, binding);
|
|
202
|
+
const mapped = mapDecision ? mapDecision(decision, ctx, execution) : { result: decision.result, reason: decision.reason };
|
|
158
203
|
return {
|
|
159
204
|
policyId: binding.policyId,
|
|
160
205
|
policyVersion: binding.version,
|
|
161
|
-
result: mapped.result,
|
|
162
|
-
reason: mapped.reason,
|
|
206
|
+
result: mapped.result ?? decision.result,
|
|
207
|
+
reason: mapped.reason ?? decision.reason,
|
|
163
208
|
metadata: {
|
|
164
209
|
...mapped.metadata ?? {},
|
|
165
210
|
opaDecision: decision
|
|
@@ -171,11 +216,16 @@ function buildSuccessOutcome(binding, engineVersion, decision, inputHash, ctx, m
|
|
|
171
216
|
dispatchPath: ["code"],
|
|
172
217
|
engine: {
|
|
173
218
|
name: ENGINE_NAME,
|
|
174
|
-
version: engineVersion,
|
|
219
|
+
version: execution.opaVersion ?? engineVersion,
|
|
175
220
|
metadata: stripUndefined({
|
|
176
221
|
decisionPath: binding.decisionPath,
|
|
177
222
|
regoPackage: binding.regoPackage,
|
|
178
223
|
inputHash,
|
|
224
|
+
decisionId: execution.decisionId,
|
|
225
|
+
bundleName: binding.bundleName,
|
|
226
|
+
bundleRevision: selection.bundleRevision,
|
|
227
|
+
bundleRevisionStatus: selection.bundleRevisionStatus,
|
|
228
|
+
provenance: execution.provenance,
|
|
179
229
|
conditionResults: decision.conditionResults,
|
|
180
230
|
factsUsed: decision.factsUsed,
|
|
181
231
|
obligations: decision.obligations
|
|
@@ -184,12 +234,13 @@ function buildSuccessOutcome(binding, engineVersion, decision, inputHash, ctx, m
|
|
|
184
234
|
}
|
|
185
235
|
};
|
|
186
236
|
}
|
|
187
|
-
function makeFailureOutcome(binding, engineVersion, error, reason, onError, inputHash) {
|
|
237
|
+
function makeFailureOutcome(binding, engineVersion, error, reason, onError, inputHash, execution) {
|
|
188
238
|
if (onError === "throw") {
|
|
189
239
|
const err = new Error(reason);
|
|
190
240
|
err.kind = error;
|
|
191
241
|
throw err;
|
|
192
242
|
}
|
|
243
|
+
const selection = execution ? selectBundleRevision(execution, binding) : {};
|
|
193
244
|
return {
|
|
194
245
|
policyId: binding.policyId,
|
|
195
246
|
policyVersion: binding.version,
|
|
@@ -205,11 +256,16 @@ function makeFailureOutcome(binding, engineVersion, error, reason, onError, inpu
|
|
|
205
256
|
dispatchPath: ["code"],
|
|
206
257
|
engine: {
|
|
207
258
|
name: ENGINE_NAME,
|
|
208
|
-
version: engineVersion,
|
|
259
|
+
version: execution?.opaVersion ?? engineVersion,
|
|
209
260
|
metadata: stripUndefined({
|
|
210
261
|
decisionPath: binding.decisionPath,
|
|
211
262
|
regoPackage: binding.regoPackage,
|
|
212
263
|
inputHash,
|
|
264
|
+
decisionId: execution?.decisionId,
|
|
265
|
+
bundleName: binding.bundleName,
|
|
266
|
+
bundleRevision: selection.bundleRevision,
|
|
267
|
+
bundleRevisionStatus: selection.bundleRevisionStatus,
|
|
268
|
+
provenance: execution?.provenance,
|
|
213
269
|
error,
|
|
214
270
|
errorReason: reason
|
|
215
271
|
})
|
|
@@ -234,9 +290,77 @@ function formatError(err) {
|
|
|
234
290
|
}
|
|
235
291
|
}
|
|
236
292
|
|
|
293
|
+
// src/executor-client.ts
|
|
294
|
+
function executorFromOpaClient(client) {
|
|
295
|
+
return {
|
|
296
|
+
async execute(path, input) {
|
|
297
|
+
const decision = await client.evaluate(path, input);
|
|
298
|
+
return { decision };
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// src/executor-http.ts
|
|
304
|
+
function executorFromOpaHttp(opts) {
|
|
305
|
+
const baseUrl = stripTrailingSlash(opts.baseUrl);
|
|
306
|
+
const provenance = opts.provenance ?? true;
|
|
307
|
+
const customFetch = opts.fetch;
|
|
308
|
+
const headers = {
|
|
309
|
+
"content-type": "application/json",
|
|
310
|
+
accept: "application/json",
|
|
311
|
+
...opts.headers ?? {}
|
|
312
|
+
};
|
|
313
|
+
return {
|
|
314
|
+
async execute(path, input) {
|
|
315
|
+
const fetchImpl = customFetch ?? globalThis.fetch;
|
|
316
|
+
if (typeof fetchImpl !== "function") {
|
|
317
|
+
throw new Error(
|
|
318
|
+
"executorFromOpaHttp: no fetch implementation available. Pass `fetch` in options or run on a runtime with `globalThis.fetch`."
|
|
319
|
+
);
|
|
320
|
+
}
|
|
321
|
+
const url = `${baseUrl}/v1/data/${stripLeadingSlash(path)}${provenance ? "?provenance=true" : ""}`;
|
|
322
|
+
const response = await fetchImpl(url, {
|
|
323
|
+
method: "POST",
|
|
324
|
+
headers,
|
|
325
|
+
body: JSON.stringify({ input })
|
|
326
|
+
});
|
|
327
|
+
if (!response.ok) {
|
|
328
|
+
const text = await safeReadText(response);
|
|
329
|
+
throw new Error(`OPA HTTP ${response.status} at ${url}: ${truncate(text, 500)}`);
|
|
330
|
+
}
|
|
331
|
+
const body = await response.json();
|
|
332
|
+
return {
|
|
333
|
+
decision: body.result,
|
|
334
|
+
decisionId: body.decision_id,
|
|
335
|
+
opaVersion: body.provenance?.version,
|
|
336
|
+
provenance: body.provenance
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
function stripTrailingSlash(s) {
|
|
342
|
+
return s.replace(/\/+$/, "");
|
|
343
|
+
}
|
|
344
|
+
function stripLeadingSlash(s) {
|
|
345
|
+
return s.replace(/^\/+/, "");
|
|
346
|
+
}
|
|
347
|
+
async function safeReadText(response) {
|
|
348
|
+
try {
|
|
349
|
+
return await response.text();
|
|
350
|
+
} catch {
|
|
351
|
+
return "<unreadable body>";
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function truncate(s, max) {
|
|
355
|
+
return s.length <= max ? s : `${s.slice(0, max)}\u2026`;
|
|
356
|
+
}
|
|
357
|
+
|
|
237
358
|
exports.createOpaPolicyEvaluator = createOpaPolicyEvaluator;
|
|
238
359
|
exports.defaultHashInput = defaultHashInput;
|
|
360
|
+
exports.executorFromOpaClient = executorFromOpaClient;
|
|
361
|
+
exports.executorFromOpaHttp = executorFromOpaHttp;
|
|
239
362
|
exports.parseOpaDecision = parseOpaDecision;
|
|
363
|
+
exports.selectBundleRevision = selectBundleRevision;
|
|
240
364
|
exports.stableStringify = stableStringify;
|
|
241
365
|
//# sourceMappingURL=index.cjs.map
|
|
242
366
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/decision-schema.ts","../src/hash.ts","../src/factory.ts"],"names":["createHash"],"mappings":";;;;;AAGA,IAAM,cAAA,GAAoD,CAAC,MAAA,EAAQ,MAAA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AA,UACrB,SAAA;AAAA,UACA,KAAA;AAAA,UACA,WAAA,EAAa;AAAA,SACb;AAAA;AACF;AACD,GACD;AACD;AAEA,SAAS,eAAe,GAAA,EAAuD;AAC9E,EAAA,MAAM,MAA+B,EAAC;AACtC,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,EAAG;AACzC,IAAA,IAAI,CAAA,KAAM,MAAA,EAAW,GAAA,CAAI,CAAC,CAAA,GAAI,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,GAAA;AACR;AAEA,SAAS,YAAY,GAAA,EAAsB;AAC1C,EAAA,IAAI,GAAA,YAAe,KAAA,EAAO,OAAO,GAAA,CAAI,OAAA;AACrC,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,EAAU,OAAO,GAAA;AACpC,EAAA,IAAI;AACH,IAAA,OAAO,IAAA,CAAK,UAAU,GAAG,CAAA;AAAA,EAC1B,CAAA,CAAA,MAAQ;AACP,IAAA,OAAO,OAAO,GAAG,CAAA;AAAA,EAClB;AACD","file":"index.cjs","sourcesContent":["import type { PolicyEvaluationResult } from \"@fabricorg/platform/policies\";\nimport type { OpaDecision } from \"./types\";\n\nconst POLICY_RESULTS: readonly PolicyEvaluationResult[] = [\"pass\", \"warn\", \"block\"];\n\nexport type OpaDecisionParseResult =\n\t| { ok: true; decision: OpaDecision }\n\t| { ok: false; error: string };\n\n/**\n * Hand-rolled validator for the Rego \"house style\" decision shape. Avoids a\n * runtime zod dependency to keep the adapter zero-dep.\n *\n * Accepts a raw OPA result and either returns the parsed `OpaDecision` or a\n * single human-readable error string describing the first violation. We don't\n * accumulate every error: when audit evidence has to record \"OPA returned\n * something invalid\", one precise reason is more useful than a list.\n */\nexport function parseOpaDecision(raw: unknown): OpaDecisionParseResult {\n\tif (raw === null || typeof raw !== \"object\") {\n\t\treturn { ok: false, error: \"decision must be an object\" };\n\t}\n\n\tconst d = raw as Record<string, unknown>;\n\n\tif (typeof d.result !== \"string\" || !POLICY_RESULTS.includes(d.result as PolicyEvaluationResult)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `result must be \"pass\" | \"warn\" | \"block\" (got ${JSON.stringify(d.result)})`,\n\t\t};\n\t}\n\n\tif (d.reason !== undefined && typeof d.reason !== \"string\") {\n\t\treturn { ok: false, error: \"reason must be a string when present\" };\n\t}\n\n\tif (d.conditionResults !== undefined) {\n\t\tif (!Array.isArray(d.conditionResults)) {\n\t\t\treturn { ok: false, error: \"conditionResults must be an array when present\" };\n\t\t}\n\t\tfor (let i = 0; i < d.conditionResults.length; i += 1) {\n\t\t\tconst err = validateConditionResult(d.conditionResults[i], i);\n\t\t\tif (err) return { ok: false, error: err };\n\t\t}\n\t}\n\n\tif (d.factsUsed !== undefined && !isPlainObject(d.factsUsed)) {\n\t\treturn { ok: false, error: \"factsUsed must be an object when present\" };\n\t}\n\n\tif (d.obligations !== undefined && !isPlainObject(d.obligations)) {\n\t\treturn { ok: false, error: \"obligations must be an object when present\" };\n\t}\n\n\treturn { ok: true, decision: d as unknown as OpaDecision };\n}\n\nfunction validateConditionResult(value: unknown, index: number): string | null {\n\tif (!isPlainObject(value)) {\n\t\treturn `conditionResults[${index}] must be an object`;\n\t}\n\tconst c = value as Record<string, unknown>;\n\tif (typeof c.conditionId !== \"string\" || c.conditionId.length === 0) {\n\t\treturn `conditionResults[${index}].conditionId must be a non-empty string`;\n\t}\n\tif (typeof c.passed !== \"boolean\") {\n\t\treturn `conditionResults[${index}].passed must be a boolean`;\n\t}\n\tif (typeof c.result !== \"string\" || !POLICY_RESULTS.includes(c.result as PolicyEvaluationResult)) {\n\t\treturn `conditionResults[${index}].result must be \"pass\" | \"warn\" | \"block\"`;\n\t}\n\tif (c.reason !== undefined && typeof c.reason !== \"string\") {\n\t\treturn `conditionResults[${index}].reason must be a string when present`;\n\t}\n\treturn null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * Stable JSON stringify — sorts object keys recursively so two\n * structurally-equal inputs produce the same string regardless of property\n * insertion order. Required for hash determinism across builds of the same\n * `buildInput` function.\n */\nexport function stableStringify(value: unknown): string {\n\tif (value === undefined) return \"null\";\n\tif (value === null || typeof value !== \"object\") return JSON.stringify(value);\n\tif (Array.isArray(value)) {\n\t\treturn `[${value.map(stableStringify).join(\",\")}]`;\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\treturn `{${keys\n\t\t.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`)\n\t\t.join(\",\")}}`;\n}\n\n/**\n * Default input hasher: SHA-256 over a stable stringification.\n * Format: `sha256:<hex>` — namespaced so future migrations to a different\n * algorithm can be detected by a prefix check in evidence dashboards.\n */\nexport function defaultHashInput(input: Record<string, unknown>): string {\n\tconst hex = createHash(\"sha256\").update(stableStringify(input)).digest(\"hex\");\n\treturn `sha256:${hex}`;\n}\n","import type {\n\tPolicyContext,\n\tPolicyEvaluator,\n\tPolicyOutcome,\n} from \"@fabricorg/platform/policies\";\n\nimport { parseOpaDecision } from \"./decision-schema\";\nimport { defaultHashInput } from \"./hash\";\nimport type {\n\tCreateOpaPolicyEvaluatorOptions,\n\tOpaDecision,\n\tOpaPolicyClient,\n\tOpaPolicyFailureKind,\n} from \"./types\";\n\nconst DEFAULT_SERVICE_KEY = \"opa\";\nconst ENGINE_NAME = \"opa\";\n\n/**\n * Build a Fabric `PolicyEvaluator` that delegates decision-making to an OPA\n * (Open Policy Agent) deployment. The evaluator:\n *\n * 1. Reads the host-injected OPA client from `ctx.services[serviceKey]`.\n * 2. Builds a JSON input snapshot via `buildInput(ctx)` — domain code that\n * snapshots facts the engine needs. Fabric platform never lets OPA reach\n * into the database directly; all facts flow through this function.\n * 3. Evaluates the Rego decision at `binding.decisionPath`.\n * 4. Validates the response against the house-style shape (`OpaDecision`).\n * 5. Maps the decision to a `PolicyOutcome` and attaches engine provenance\n * (`engine.name = \"opa\"`, `decisionPath`, `inputHash`) for audit.\n *\n * Failures (missing client, build failure, network failure, malformed response)\n * are governed by `onError`. Default `\"block\"` honors Fabric's default-deny\n * posture and records the failure category under `engine.metadata.error`.\n */\nexport function createOpaPolicyEvaluator<TDb = unknown>(\n\toptions: CreateOpaPolicyEvaluatorOptions<TDb>,\n): PolicyEvaluator<TDb> {\n\tconst {\n\t\tbinding,\n\t\tbuildInput,\n\t\tserviceKey = DEFAULT_SERVICE_KEY,\n\t\tonError = \"block\",\n\t\tpreviewSafe = false,\n\t\tengineVersion,\n\t\tmapDecision,\n\t\thashInput = defaultHashInput,\n\t} = options;\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tversion: binding.version,\n\t\tpreviewSafe,\n\t\tevaluate: async (ctx) => {\n\t\t\tconst client = ctx.services?.[serviceKey] as OpaPolicyClient | undefined;\n\t\t\tif (!client || typeof client.evaluate !== \"function\") {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"client_unavailable\",\n\t\t\t\t\t`No OPA client at ctx.services[\"${serviceKey}\"]`,\n\t\t\t\t\tonError,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet input: Record<string, unknown>;\n\t\t\ttry {\n\t\t\t\tinput = await buildInput(ctx);\n\t\t\t} catch (err) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"input_build_failed\",\n\t\t\t\t\t`buildInput threw: ${formatError(err)}`,\n\t\t\t\t\tonError,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet inputHash: string | undefined;\n\t\t\ttry {\n\t\t\t\tinputHash = hashInput(input);\n\t\t\t} catch {\n\t\t\t\t// hashing is best-effort — if a custom hasher throws, omit the\n\t\t\t\t// field rather than fail the policy.\n\t\t\t}\n\n\t\t\tlet rawResult: unknown;\n\t\t\ttry {\n\t\t\t\trawResult = await client.evaluate(binding.decisionPath, input);\n\t\t\t} catch (err) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"evaluation_failed\",\n\t\t\t\t\t`OPA evaluation failed: ${formatError(err)}`,\n\t\t\t\t\tonError,\n\t\t\t\t\tinputHash,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst parsed = parseOpaDecision(rawResult);\n\t\t\tif (!parsed.ok) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"invalid_response\",\n\t\t\t\t\t`OPA returned malformed decision: ${parsed.error}`,\n\t\t\t\t\tonError,\n\t\t\t\t\tinputHash,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn buildSuccessOutcome(\n\t\t\t\tbinding,\n\t\t\t\tengineVersion,\n\t\t\t\tparsed.decision,\n\t\t\t\tinputHash,\n\t\t\t\tctx,\n\t\t\t\tmapDecision,\n\t\t\t);\n\t\t},\n\t};\n}\n\nfunction buildSuccessOutcome<TDb>(\n\tbinding: CreateOpaPolicyEvaluatorOptions<TDb>[\"binding\"],\n\tengineVersion: string | undefined,\n\tdecision: OpaDecision,\n\tinputHash: string | undefined,\n\tctx: PolicyContext<TDb>,\n\tmapDecision: CreateOpaPolicyEvaluatorOptions<TDb>[\"mapDecision\"],\n): PolicyOutcome {\n\tconst mapped = mapDecision\n\t\t? mapDecision(decision, ctx)\n\t\t: { result: decision.result, reason: decision.reason };\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tpolicyVersion: binding.version,\n\t\tresult: mapped.result,\n\t\treason: mapped.reason,\n\t\tmetadata: {\n\t\t\t...(mapped.metadata ?? {}),\n\t\t\topaDecision: decision,\n\t\t},\n\t\tdispatchEvidence: {\n\t\t\tpolicyKind: \"code\",\n\t\t\tpolicyId: binding.policyId,\n\t\t\tpolicyVersion: binding.version,\n\t\t\tdispatchPath: [\"code\"],\n\t\t\tengine: {\n\t\t\t\tname: ENGINE_NAME,\n\t\t\t\tversion: engineVersion,\n\t\t\t\tmetadata: stripUndefined({\n\t\t\t\t\tdecisionPath: binding.decisionPath,\n\t\t\t\t\tregoPackage: binding.regoPackage,\n\t\t\t\t\tinputHash,\n\t\t\t\t\tconditionResults: decision.conditionResults,\n\t\t\t\t\tfactsUsed: decision.factsUsed,\n\t\t\t\t\tobligations: decision.obligations,\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction makeFailureOutcome(\n\tbinding: CreateOpaPolicyEvaluatorOptions[\"binding\"],\n\tengineVersion: string | undefined,\n\terror: OpaPolicyFailureKind,\n\treason: string,\n\tonError: \"block\" | \"throw\",\n\tinputHash?: string,\n): PolicyOutcome {\n\tif (onError === \"throw\") {\n\t\tconst err = new Error(reason);\n\t\t(err as Error & { kind?: OpaPolicyFailureKind }).kind = error;\n\t\tthrow err;\n\t}\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tpolicyVersion: binding.version,\n\t\tresult: \"block\",\n\t\treason,\n\t\tmetadata: {\n\t\t\topaError: error,\n\t\t},\n\t\tdispatchEvidence: {\n\t\t\tpolicyKind: \"code\",\n\t\t\tpolicyId: binding.policyId,\n\t\t\tpolicyVersion: binding.version,\n\t\t\tdispatchPath: [\"code\"],\n\t\t\tengine: {\n\t\t\t\tname: ENGINE_NAME,\n\t\t\t\tversion: engineVersion,\n\t\t\t\tmetadata: stripUndefined({\n\t\t\t\t\tdecisionPath: binding.decisionPath,\n\t\t\t\t\tregoPackage: binding.regoPackage,\n\t\t\t\t\tinputHash,\n\t\t\t\t\terror,\n\t\t\t\t\terrorReason: reason,\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction stripUndefined(obj: Record<string, unknown>): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(obj)) {\n\t\tif (v !== undefined) out[k] = v;\n\t}\n\treturn out;\n}\n\nfunction formatError(err: unknown): string {\n\tif (err instanceof Error) return err.message;\n\tif (typeof err === \"string\") return err;\n\ttry {\n\t\treturn JSON.stringify(err);\n\t} catch {\n\t\treturn String(err);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/bundle-selector.ts","../src/decision-schema.ts","../src/hash.ts","../src/factory.ts","../src/executor-client.ts","../src/executor-http.ts"],"names":["createHash"],"mappings":";;;;;AA0BO,SAAS,oBAAA,CACf,WACA,OAAA,EACkB;AAClB,EAAA,IAAI,OAAO,SAAA,CAAU,cAAA,KAAmB,YAAY,SAAA,CAAU,cAAA,CAAe,SAAS,CAAA,EAAG;AACxF,IAAA,OAAO,EAAE,cAAA,EAAgB,SAAA,CAAU,cAAA,EAAe;AAAA,EACnD;AAEA,EAAA,MAAM,OAAA,GAAU,WAAA,CAAY,SAAA,CAAU,UAAU,CAAA;AAChD,EAAA,IAAI,CAAC,OAAA,EAAS,OAAO,EAAC;AAEtB,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA;AACjC,EAAA,IAAI,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG,OAAO,EAAC;AAEhC,EAAA,IAAI,QAAQ,UAAA,EAAY;AACvB,IAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,OAAA,CAAQ,UAAU,CAAA,EAAG,QAAA;AAC9C,IAAA,OAAO,OAAO,QAAA,KAAa,QAAA,IAAY,QAAA,CAAS,MAAA,GAAS,IACtD,EAAE,cAAA,EAAgB,QAAA,EAAS,GAC3B,EAAC;AAAA,EACL;AAEA,EAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACvB,IAAA,MAAM,IAAA,GAAO,MAAM,CAAC,CAAA;AAGpB,IAAA,MAAM,WAAW,IAAA,KAAS,MAAA,GAAY,OAAA,CAAQ,IAAI,GAAG,QAAA,GAAW,MAAA;AAChE,IAAA,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CAAa,QAAQ,CAAA;AACxC,QAAA,MAAM,IAAI,KAAA,CAAM,CAAA,SAAA,EAAY,QAAA,CAAS,MAAM,CAAA,IAAA,EAAO,GAAG,CAAA,EAAA,EAAK,QAAA,CAAS,IAAA,EAAM,GAAG,CAAC,CAAA,CAAE,CAAA;AAAA,MAChF;AAEA,MAAA,MAAM,IAAA,GAAQ,MAAM,QAAA,CAAS,IAAA,EAAK;AAElC,MAAA,OAAO;AAAA,QACN,UAAU,IAAA,CAAK,MAAA;AAAA,QACf,YAAY,IAAA,CAAK,WAAA;AAAA,QACjB,UAAA,EAAY,KAAK,UAAA,EAAY,OAAA;AAAA,QAC7B,YAAY,IAAA,CAAK;AAAA,OAClB;AAAA,IACD;AAAA,GACD;AACD;AAEA,SAAS,mBAAmB,CAAA,EAAmB;AAC9C,EAAA,OAAO,CAAA,CAAE,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AAC5B;AAEA,SAAS,kBAAkB,CAAA,EAAmB;AAC7C,EAAA,OAAO,CAAA,CAAE,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AAC5B;AAEA,eAAe,aAAa,QAAA,EAAqC;AAChE,EAAA,IAAI;AACH,IAAA,OAAO,MAAM,SAAS,IAAA,EAAK;AAAA,EAC5B,CAAA,CAAA,MAAQ;AACP,IAAA,OAAO,mBAAA;AAAA,EACR;AACD;AAEA,SAAS,QAAA,CAAS,GAAW,GAAA,EAAqB;AACjD,EAAA,OAAO,CAAA,CAAE,UAAU,GAAA,GAAM,CAAA,GAAI,GAAG,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,GAAG,CAAC,CAAA,MAAA,CAAA;AAChD","file":"index.cjs","sourcesContent":["import type { OpaPolicyBinding, OpaPolicyExecution } from \"./types\";\n\nexport interface BundleSelection {\n\tbundleRevision?: string;\n\t/**\n\t * Set to `\"ambiguous\"` when OPA reports multiple bundles and the binding\n\t * did not pick one with `bundleName`. The adapter records this on the\n\t * evidence so dashboards can flag policies that need explicit selectors.\n\t * `\"missing\"` is set when provenance was expected but absent.\n\t */\n\tbundleRevisionStatus?: \"ambiguous\" | \"missing\";\n}\n\n/**\n * Determine which OPA bundle revision applies to this decision.\n *\n * Rules (in order):\n * 1. If the executor already populated `execution.bundleRevision`, use it.\n * 2. If `binding.bundleName` is set, look it up in `provenance.bundles`.\n * 3. If exactly one bundle is reported, use its revision unambiguously.\n * 4. If multiple bundles are reported and no selector exists, mark\n * `bundleRevisionStatus: \"ambiguous\"`.\n * 5. If no provenance is reported at all, return `{}` — the caller decides\n * whether absence is meaningful (it is not, for executors that don't\n * carry provenance).\n */\nexport function selectBundleRevision(\n\texecution: OpaPolicyExecution,\n\tbinding: OpaPolicyBinding,\n): BundleSelection {\n\tif (typeof execution.bundleRevision === \"string\" && execution.bundleRevision.length > 0) {\n\t\treturn { bundleRevision: execution.bundleRevision };\n\t}\n\n\tconst bundles = readBundles(execution.provenance);\n\tif (!bundles) return {};\n\n\tconst names = Object.keys(bundles);\n\tif (names.length === 0) return {};\n\n\tif (binding.bundleName) {\n\t\tconst revision = bundles[binding.bundleName]?.revision;\n\t\treturn typeof revision === \"string\" && revision.length > 0\n\t\t\t? { bundleRevision: revision }\n\t\t\t: {};\n\t}\n\n\tif (names.length === 1) {\n\t\tconst only = names[0];\n\t\t// names.length === 1 guarantees names[0] is defined, but the\n\t\t// non-null assertion satisfies noUncheckedIndexedAccess if enabled.\n\t\tconst revision = only !== undefined ? bundles[only]?.revision : undefined;\n\t\treturn typeof revision === \"string\" && revision.length > 0\n\t\t\t? { bundleRevision: revision }\n\t\t\t: {};\n\t}\n\n\treturn { bundleRevisionStatus: \"ambiguous\" };\n}\n\nfunction readBundles(\n\tprovenance: Record<string, unknown> | undefined,\n): Record<string, { revision?: unknown }> | undefined {\n\tif (!provenance || typeof provenance !== \"object\") return undefined;\n\tconst b = (provenance as { bundles?: unknown }).bundles;\n\tif (!b || typeof b !== \"object\" || Array.isArray(b)) return undefined;\n\treturn b as Record<string, { revision?: unknown }>;\n}\n","import type { PolicyEvaluationResult } from \"@fabricorg/platform/policies\";\nimport type { OpaDecision } from \"./types\";\n\nconst POLICY_RESULTS: readonly PolicyEvaluationResult[] = [\"pass\", \"warn\", \"block\"];\n\nexport type OpaDecisionParseResult =\n\t| { ok: true; decision: OpaDecision }\n\t| { ok: false; error: string };\n\n/**\n * Hand-rolled validator for the Rego \"house style\" decision shape. Avoids a\n * runtime zod dependency to keep the adapter zero-dep.\n *\n * Accepts a raw OPA result and either returns the parsed `OpaDecision` or a\n * single human-readable error string describing the first violation. We don't\n * accumulate every error: when audit evidence has to record \"OPA returned\n * something invalid\", one precise reason is more useful than a list.\n */\nexport function parseOpaDecision(raw: unknown): OpaDecisionParseResult {\n\tif (raw === null || typeof raw !== \"object\") {\n\t\treturn { ok: false, error: \"decision must be an object\" };\n\t}\n\n\tconst d = raw as Record<string, unknown>;\n\n\tif (typeof d.result !== \"string\" || !POLICY_RESULTS.includes(d.result as PolicyEvaluationResult)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `result must be \"pass\" | \"warn\" | \"block\" (got ${JSON.stringify(d.result)})`,\n\t\t};\n\t}\n\n\tif (d.reason !== undefined && typeof d.reason !== \"string\") {\n\t\treturn { ok: false, error: \"reason must be a string when present\" };\n\t}\n\n\tif (d.conditionResults !== undefined) {\n\t\tif (!Array.isArray(d.conditionResults)) {\n\t\t\treturn { ok: false, error: \"conditionResults must be an array when present\" };\n\t\t}\n\t\tfor (let i = 0; i < d.conditionResults.length; i += 1) {\n\t\t\tconst err = validateConditionResult(d.conditionResults[i], i);\n\t\t\tif (err) return { ok: false, error: err };\n\t\t}\n\t}\n\n\tif (d.factsUsed !== undefined && !isPlainObject(d.factsUsed)) {\n\t\treturn { ok: false, error: \"factsUsed must be an object when present\" };\n\t}\n\n\tif (d.obligations !== undefined && !isPlainObject(d.obligations)) {\n\t\treturn { ok: false, error: \"obligations must be an object when present\" };\n\t}\n\n\treturn { ok: true, decision: d as unknown as OpaDecision };\n}\n\nfunction validateConditionResult(value: unknown, index: number): string | null {\n\tif (!isPlainObject(value)) {\n\t\treturn `conditionResults[${index}] must be an object`;\n\t}\n\tconst c = value as Record<string, unknown>;\n\tif (typeof c.conditionId !== \"string\" || c.conditionId.length === 0) {\n\t\treturn `conditionResults[${index}].conditionId must be a non-empty string`;\n\t}\n\tif (typeof c.passed !== \"boolean\") {\n\t\treturn `conditionResults[${index}].passed must be a boolean`;\n\t}\n\tif (typeof c.result !== \"string\" || !POLICY_RESULTS.includes(c.result as PolicyEvaluationResult)) {\n\t\treturn `conditionResults[${index}].result must be \"pass\" | \"warn\" | \"block\"`;\n\t}\n\tif (c.reason !== undefined && typeof c.reason !== \"string\") {\n\t\treturn `conditionResults[${index}].reason must be a string when present`;\n\t}\n\treturn null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * Stable JSON stringify — sorts object keys recursively so two\n * structurally-equal inputs produce the same string regardless of property\n * insertion order. Required for hash determinism across builds of the same\n * `buildInput` function.\n */\nexport function stableStringify(value: unknown): string {\n\tif (value === undefined) return \"null\";\n\tif (value === null || typeof value !== \"object\") return JSON.stringify(value);\n\tif (Array.isArray(value)) {\n\t\treturn `[${value.map(stableStringify).join(\",\")}]`;\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\treturn `{${keys\n\t\t.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`)\n\t\t.join(\",\")}}`;\n}\n\n/**\n * Default input hasher: SHA-256 over a stable stringification.\n * Format: `sha256:<hex>` — namespaced so future migrations to a different\n * algorithm can be detected by a prefix check in evidence dashboards.\n */\nexport function defaultHashInput(input: Record<string, unknown>): string {\n\tconst hex = createHash(\"sha256\").update(stableStringify(input)).digest(\"hex\");\n\treturn `sha256:${hex}`;\n}\n","import type {\n\tPolicyContext,\n\tPolicyEvaluator,\n\tPolicyOutcome,\n} from \"@fabricorg/platform/policies\";\n\nimport { selectBundleRevision } from \"./bundle-selector\";\nimport { parseOpaDecision } from \"./decision-schema\";\nimport { defaultHashInput } from \"./hash\";\nimport type {\n\tCreateOpaPolicyEvaluatorOptions,\n\tOpaDecision,\n\tOpaPolicyBinding,\n\tOpaPolicyClient,\n\tOpaPolicyExecution,\n\tOpaPolicyExecutor,\n\tOpaPolicyFailureKind,\n} from \"./types\";\n\nconst DEFAULT_SERVICE_KEY = \"opa\";\nconst ENGINE_NAME = \"opa\";\n\n/**\n * Build a Fabric `PolicyEvaluator` that delegates decision-making to an OPA\n * (Open Policy Agent) deployment.\n *\n * The adapter accepts either of two service shapes under\n * `ctx.services[serviceKey]`:\n *\n * - `OpaPolicyExecutor` (preferred) — `execute(path, input)` returning a rich\n * `OpaPolicyExecution` (decision plus `decisionId`, `bundleRevision`,\n * `opaVersion`, `provenance`). Ship one with {@link executorFromOpaHttp} or\n * {@link executorFromOpaClient}.\n * - `OpaPolicyClient` — `evaluate(path, input)` returning the raw decision\n * only. Compatible with the high-level `@open-policy-agent/opa` SDK at the\n * cost of OPA-side provenance.\n *\n * If both methods are present, `execute` is preferred.\n *\n * The evaluator:\n *\n * 1. Resolves the service from `ctx.services[serviceKey]`.\n * 2. Builds a JSON input snapshot via `buildInput(ctx)` — domain code that\n * snapshots facts the engine needs. OPA never reaches into the database\n * directly; all facts flow through this function.\n * 3. Calls OPA at `binding.decisionPath`.\n * 4. Validates the response against the house-style shape (`OpaDecision`).\n * 5. Maps the decision to a `PolicyOutcome` and attaches engine provenance\n * under `dispatchEvidence.engine` — `name`, optional `version`, and\n * metadata covering `decisionPath`, `regoPackage`, `inputHash`, plus (when\n * the executor surfaces them) `decisionId`, `bundleName`, `bundleRevision`,\n * `bundleRevisionStatus`, and the raw `provenance` block.\n *\n * Failures (missing client, build failure, network failure, malformed\n * response) are governed by `onError`. Default `\"block\"` honors Fabric's\n * default-deny posture and records the failure category under\n * `engine.metadata.error`.\n */\nexport function createOpaPolicyEvaluator<TDb = unknown>(\n\toptions: CreateOpaPolicyEvaluatorOptions<TDb>,\n): PolicyEvaluator<TDb> {\n\tconst {\n\t\tbinding,\n\t\tbuildInput,\n\t\tserviceKey = DEFAULT_SERVICE_KEY,\n\t\tonError = \"block\",\n\t\tpreviewSafe = false,\n\t\tengineVersion,\n\t\tmapDecision,\n\t\thashInput = defaultHashInput,\n\t} = options;\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tversion: binding.version,\n\t\tpreviewSafe,\n\t\tevaluate: async (ctx) => {\n\t\t\tconst service = ctx.services?.[serviceKey];\n\t\t\tconst transport = resolveTransport(service);\n\t\t\tif (!transport) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"client_unavailable\",\n\t\t\t\t\t`No OPA client/executor at ctx.services[\"${serviceKey}\"]`,\n\t\t\t\t\tonError,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet input: Record<string, unknown>;\n\t\t\ttry {\n\t\t\t\tinput = await buildInput(ctx);\n\t\t\t} catch (err) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"input_build_failed\",\n\t\t\t\t\t`buildInput threw: ${formatError(err)}`,\n\t\t\t\t\tonError,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet inputHash: string | undefined;\n\t\t\ttry {\n\t\t\t\tinputHash = hashInput(input);\n\t\t\t} catch {\n\t\t\t\t// hashing is best-effort — if a custom hasher throws, omit the\n\t\t\t\t// field rather than fail the policy.\n\t\t\t}\n\n\t\t\tlet execution: OpaPolicyExecution;\n\t\t\ttry {\n\t\t\t\texecution = await transport(binding.decisionPath, input);\n\t\t\t} catch (err) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"evaluation_failed\",\n\t\t\t\t\t`OPA evaluation failed: ${formatError(err)}`,\n\t\t\t\t\tonError,\n\t\t\t\t\tinputHash,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst parsed = parseOpaDecision(execution.decision);\n\t\t\tif (!parsed.ok) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"invalid_response\",\n\t\t\t\t\t`OPA returned malformed decision: ${parsed.error}`,\n\t\t\t\t\tonError,\n\t\t\t\t\tinputHash,\n\t\t\t\t\texecution,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn buildSuccessOutcome(\n\t\t\t\tbinding,\n\t\t\t\tengineVersion,\n\t\t\t\tparsed.decision,\n\t\t\t\texecution,\n\t\t\t\tinputHash,\n\t\t\t\tctx,\n\t\t\t\tmapDecision,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Discriminates between the rich executor shape and the legacy client shape.\n * Returns a uniform `(path, input) => OpaPolicyExecution` transport, or\n * `null` if the service doesn't implement either contract.\n *\n * `execute` is preferred when both are present so a v0.1 client wrapped by a\n * richer executor still wins.\n */\nfunction resolveTransport(\n\tservice: unknown,\n): ((path: string, input: unknown) => Promise<OpaPolicyExecution>) | null {\n\tif (!service || typeof service !== \"object\") return null;\n\tconst exec = (service as Partial<OpaPolicyExecutor>).execute;\n\tif (typeof exec === \"function\") {\n\t\treturn (path, input) => (service as OpaPolicyExecutor).execute(path, input);\n\t}\n\tconst eval_ = (service as Partial<OpaPolicyClient>).evaluate;\n\tif (typeof eval_ === \"function\") {\n\t\treturn async (path, input) => ({\n\t\t\tdecision: await (service as OpaPolicyClient).evaluate(path, input),\n\t\t});\n\t}\n\treturn null;\n}\n\nfunction buildSuccessOutcome<TDb>(\n\tbinding: OpaPolicyBinding,\n\tengineVersion: string | undefined,\n\tdecision: OpaDecision,\n\texecution: OpaPolicyExecution,\n\tinputHash: string | undefined,\n\tctx: PolicyContext<TDb>,\n\tmapDecision: CreateOpaPolicyEvaluatorOptions<TDb>[\"mapDecision\"],\n): PolicyOutcome {\n\tconst selection = selectBundleRevision(execution, binding);\n\tconst mapped = mapDecision\n\t\t? mapDecision(decision, ctx, execution)\n\t\t: { result: decision.result, reason: decision.reason };\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tpolicyVersion: binding.version,\n\t\tresult: mapped.result ?? decision.result,\n\t\treason: mapped.reason ?? decision.reason,\n\t\tmetadata: {\n\t\t\t...(mapped.metadata ?? {}),\n\t\t\topaDecision: decision,\n\t\t},\n\t\tdispatchEvidence: {\n\t\t\tpolicyKind: \"code\",\n\t\t\tpolicyId: binding.policyId,\n\t\t\tpolicyVersion: binding.version,\n\t\t\tdispatchPath: [\"code\"],\n\t\t\tengine: {\n\t\t\t\tname: ENGINE_NAME,\n\t\t\t\tversion: execution.opaVersion ?? engineVersion,\n\t\t\t\tmetadata: stripUndefined({\n\t\t\t\t\tdecisionPath: binding.decisionPath,\n\t\t\t\t\tregoPackage: binding.regoPackage,\n\t\t\t\t\tinputHash,\n\t\t\t\t\tdecisionId: execution.decisionId,\n\t\t\t\t\tbundleName: binding.bundleName,\n\t\t\t\t\tbundleRevision: selection.bundleRevision,\n\t\t\t\t\tbundleRevisionStatus: selection.bundleRevisionStatus,\n\t\t\t\t\tprovenance: execution.provenance,\n\t\t\t\t\tconditionResults: decision.conditionResults,\n\t\t\t\t\tfactsUsed: decision.factsUsed,\n\t\t\t\t\tobligations: decision.obligations,\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction makeFailureOutcome(\n\tbinding: OpaPolicyBinding,\n\tengineVersion: string | undefined,\n\terror: OpaPolicyFailureKind,\n\treason: string,\n\tonError: \"block\" | \"throw\",\n\tinputHash?: string,\n\texecution?: OpaPolicyExecution,\n): PolicyOutcome {\n\tif (onError === \"throw\") {\n\t\tconst err = new Error(reason);\n\t\t(err as Error & { kind?: OpaPolicyFailureKind }).kind = error;\n\t\tthrow err;\n\t}\n\n\tconst selection = execution ? selectBundleRevision(execution, binding) : {};\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tpolicyVersion: binding.version,\n\t\tresult: \"block\",\n\t\treason,\n\t\tmetadata: {\n\t\t\topaError: error,\n\t\t},\n\t\tdispatchEvidence: {\n\t\t\tpolicyKind: \"code\",\n\t\t\tpolicyId: binding.policyId,\n\t\t\tpolicyVersion: binding.version,\n\t\t\tdispatchPath: [\"code\"],\n\t\t\tengine: {\n\t\t\t\tname: ENGINE_NAME,\n\t\t\t\tversion: execution?.opaVersion ?? engineVersion,\n\t\t\t\tmetadata: stripUndefined({\n\t\t\t\t\tdecisionPath: binding.decisionPath,\n\t\t\t\t\tregoPackage: binding.regoPackage,\n\t\t\t\t\tinputHash,\n\t\t\t\t\tdecisionId: execution?.decisionId,\n\t\t\t\t\tbundleName: binding.bundleName,\n\t\t\t\t\tbundleRevision: selection.bundleRevision,\n\t\t\t\t\tbundleRevisionStatus: selection.bundleRevisionStatus,\n\t\t\t\t\tprovenance: execution?.provenance,\n\t\t\t\t\terror,\n\t\t\t\t\terrorReason: reason,\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction stripUndefined(obj: Record<string, unknown>): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(obj)) {\n\t\tif (v !== undefined) out[k] = v;\n\t}\n\treturn out;\n}\n\nfunction formatError(err: unknown): string {\n\tif (err instanceof Error) return err.message;\n\tif (typeof err === \"string\") return err;\n\ttry {\n\t\treturn JSON.stringify(err);\n\t} catch {\n\t\treturn String(err);\n\t}\n}\n","import type {\n\tOpaPolicyClient,\n\tOpaPolicyExecution,\n\tOpaPolicyExecutor,\n} from \"./types\";\n\n/**\n * Wrap an `OpaPolicyClient` (the high-level `@open-policy-agent/opa` SDK\n * shape) as an {@link OpaPolicyExecutor}. The resulting executor carries no\n * OPA-side provenance — the high-level SDK discards `decisionId` and\n * `provenance` from the response — but does centralize the\n * `(path, input) => execution` plumbing so hosts can choose at startup whether\n * to wire a client or a full executor.\n *\n * For full provenance (decisionId, bundleRevision, opaVersion), prefer\n * {@link executorFromOpaHttp}.\n */\nexport function executorFromOpaClient(client: OpaPolicyClient): OpaPolicyExecutor {\n\treturn {\n\t\tasync execute(path: string, input: unknown): Promise<OpaPolicyExecution> {\n\t\t\tconst decision = await client.evaluate(path, input);\n\t\t\treturn { decision };\n\t\t},\n\t};\n}\n","import type { OpaPolicyExecution, OpaPolicyExecutor } from \"./types\";\n\nexport interface OpaHttpExecutorOptions {\n\t/**\n\t * Base URL of the OPA server, e.g. `\"http://localhost:8181\"` or\n\t * `\"https://opa.internal.example.com\"`. Trailing slash is permitted; the\n\t * executor normalizes it.\n\t */\n\tbaseUrl: string;\n\t/**\n\t * Override for `globalThis.fetch`. Lets the host inject a fetch instance\n\t * with retries, mTLS, OpenTelemetry instrumentation, etc. Defaults to\n\t * `globalThis.fetch`.\n\t */\n\tfetch?: typeof globalThis.fetch;\n\t/** Extra request headers (e.g. `Authorization`). */\n\theaders?: Record<string, string>;\n\t/**\n\t * Request OPA-side provenance (`decision_id`, `provenance.version`,\n\t * `provenance.bundles[*].revision`) via `?provenance=true`. Defaults to\n\t * `true` — turning it off forfeits OPA's contribution to audit evidence\n\t * and is rarely what you want.\n\t */\n\tprovenance?: boolean;\n}\n\ninterface OpaHttpResponseBody {\n\tresult?: unknown;\n\tdecision_id?: string;\n\tprovenance?: {\n\t\tversion?: string;\n\t\tbuild_commit?: string;\n\t\tbuild_timestamp?: string;\n\t\tbuild_host?: string;\n\t\tbundles?: Record<string, { revision?: string }>;\n\t};\n}\n\n/**\n * Build an {@link OpaPolicyExecutor} that talks to OPA's REST API directly.\n *\n * POSTs to `{baseUrl}/v1/data/{path}?provenance=true` with body\n * `{ \"input\": ... }`. Parses the snake_case response and lifts:\n *\n * - `result` → `execution.decision`\n * - `decision_id` → `execution.decisionId`\n * - `provenance.version` → `execution.opaVersion`\n * - `provenance` (whole block) → `execution.provenance`\n *\n * Bundle revision selection happens in the factory, not the executor, because\n * it depends on `binding.bundleName`.\n *\n * Calling this in environments without `globalThis.fetch` (older Node) throws\n * at call time; pass `fetch: nodeFetch` or `fetch: undici-fetch` etc. via the\n * options to support those runtimes explicitly.\n */\nexport function executorFromOpaHttp(opts: OpaHttpExecutorOptions): OpaPolicyExecutor {\n\tconst baseUrl = stripTrailingSlash(opts.baseUrl);\n\tconst provenance = opts.provenance ?? true;\n\tconst customFetch = opts.fetch;\n\tconst headers = {\n\t\t\"content-type\": \"application/json\",\n\t\taccept: \"application/json\",\n\t\t...(opts.headers ?? {}),\n\t};\n\n\treturn {\n\t\tasync execute(path: string, input: unknown): Promise<OpaPolicyExecution> {\n\t\t\tconst fetchImpl = customFetch ?? globalThis.fetch;\n\t\t\tif (typeof fetchImpl !== \"function\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"executorFromOpaHttp: no fetch implementation available. Pass `fetch` in options or run on a runtime with `globalThis.fetch`.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst url = `${baseUrl}/v1/data/${stripLeadingSlash(path)}${\n\t\t\t\tprovenance ? \"?provenance=true\" : \"\"\n\t\t\t}`;\n\t\t\tconst response = await fetchImpl(url, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders,\n\t\t\t\tbody: JSON.stringify({ input }),\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst text = await safeReadText(response);\n\t\t\t\tthrow new Error(`OPA HTTP ${response.status} at ${url}: ${truncate(text, 500)}`);\n\t\t\t}\n\n\t\t\tconst body = (await response.json()) as OpaHttpResponseBody;\n\n\t\t\treturn {\n\t\t\t\tdecision: body.result,\n\t\t\t\tdecisionId: body.decision_id,\n\t\t\t\topaVersion: body.provenance?.version,\n\t\t\t\tprovenance: body.provenance as Record<string, unknown> | undefined,\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction stripTrailingSlash(s: string): string {\n\treturn s.replace(/\\/+$/, \"\");\n}\n\nfunction stripLeadingSlash(s: string): string {\n\treturn s.replace(/^\\/+/, \"\");\n}\n\nasync function safeReadText(response: Response): Promise<string> {\n\ttry {\n\t\treturn await response.text();\n\t} catch {\n\t\treturn \"<unreadable body>\";\n\t}\n}\n\nfunction truncate(s: string, max: number): string {\n\treturn s.length <= max ? s : `${s.slice(0, max)}…`;\n}\n"]}
|